How to specify object custom serialization in ORMLite?

后端 未结 2 1260
逝去的感伤
逝去的感伤 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条回答
  • 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;
    
    0 讨论(0)
  • 2021-01-21 20:37

    Don't register the persister adapter in the onCreate() method. This method only gets called when your database is first created. You should add this somewhere else, like your constructor or onOpen() method.

    0 讨论(0)
提交回复
热议问题