How to specify object custom serialization in ORMLite?

后端 未结 2 1261
逝去的感伤
逝去的感伤 2021-01-21 19:55

I would like to store some field of type ParentClass as json string into my database. I don\'t want to use Serializable interface and DataType.SERIALIZABLE cause it ties with fu

2条回答
  •  -上瘾入骨i
    2021-01-21 20:15

    So basically your persister should be implemented in the next way:

    public class MyFieldClassPersister extends StringType {
    
        private static final MyFieldClassPersister INSTANCE = new MyFieldClassPersister();
    
        private MyFieldClassPersister() {
            super(SqlType.STRING, new Class[] { MyFieldClass.class });
        }
    
        public static MyFieldClassPersister getSingleton() {
            return INSTANCE;
        }
    
        @Override
        public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
            MyFieldClass myFieldClass = (MyFieldClass) javaObject;
            return myFieldClass != null ? getJsonFromMyFieldClass(myFieldClass) : null;
        }
    
        @Override
        public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
            return sqlArg != null ? getMyFieldClassFromJson((String) sqlArg) : null;
        }
    
        private String getJsonFromMyFieldClass(MyFieldClass myFieldClass) {
            // logic here
        }
    
        private MyFieldClass getMyFieldClassFromJson(String json) {
            // logic here
        }
    }
    

    You should register it in onCreate method of your OrmLiteSqliteOpenHelper class

        @Override
        public void onCreate(SQLiteDatabaseHolder holder, ConnectionSource connectionSource) {
                try {
                    //...
                    DataPersisterManager
                     .registerDataPersisters(MyFieldClassPersister.getSingleton());
                } catch (SQLException e) {
                    // log exception
                }
        }
    

    And then you can use it in your model like this:

    @DatabaseField(persisterClass = MyFieldClassPersister.class, columnName = "column_name")
    protected MyFieldClass myFieldClass;
    

提交回复
热议问题