Data lost because of JPA AttributeConverter?

前端 未结 1 973
逝去的感伤
逝去的感伤 2021-01-18 20:48

I use JPA to persist my data to the database. In detail I use Hibernate 4.3.5 as JPA implementation. Because of performance and keeping the table structure simple, I don not

相关标签:
1条回答
  • 2021-01-18 20:58

    I know it's an old question, but...

    I've had the same problem with Hibernate+@Converter once. After a while, I realized that's because Hibernate doesn't know when the left side of AttributeConverter<left,right> gets dirty (maybe some other JPA implementations do), that's why it never calls convertToDatabaseColumn() and therefore never updates the database.

    To work around this issue, you must set the entity's property to a fresh new instance (a clone() would do the trick).

    EntitySample entity=new EntitySample();
    entity.getSampleList().add(new SampleObject("A"));
    entity.getSampleList().add(new SampleObject("B"));
    entity.getSampleList().add(new SampleObject("C"));
    entity.setName("init");
    startTransaction();
    getEM().persist(entity);
    commitTransaction();
    
    // change the order to A, C, B:
    getEM().clear();
    startTransaction();  // <-- Transaction should start here
    EntitySample loaded=getEM().find(...);
    List<SampleObject> list = loaded.getSampleList();
    SampleObject moveObj = list.remove(1);
    list.add(moveObj);
    loaded.setSampleList(list.clone()); // <-- Workaround
    
    // getEM().merge(loaded); // <-- 'loaded' already is an entity!
    commitTransaction();
    

    Here clone() returns a shallow copy of the List instance. (The instances of SampleObject themselves are not copied.)

    To avoid this you have to create a new Hibernate Type (leaving pure JPA aside), but that's not related to the main question.

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