问题描述
我有一个Hibernate模型,它使用自定义类型来表示布尔字段(即模型有一个'Boolean'对象,但数据库将0或1写入TINYINT字段。更改布尔对象的值from(true to false或false to true)将更改对象的值,但Hibernate会话管理器似乎认为对象没有任何值更改,因此 save()
实际上并没有将SQL写入数据库。
I've got a Hibernate model that uses a custom type to represent boolean fields (ie, model has a 'Boolean' object, but the database writes a 0 or 1 to a TINYINT field. Changing the value of the boolean object from (true to false or false to true) will change the value on the object, but the Hibernate session manager doesn't seem to think the object had any values change, and therefore save()
does not actually write SQL to the DB.
我是否需要在自定义类型中执行一些特殊操作才能让它看到更改?我更喜欢强迫每个对象在访问器中脏,但这也是可能的。
Do I need to do something special in my custom type to get it to see changes? I'd prefer that to forcing each object to 'dirty' itself in accessors, but that's also possible.
推荐答案
有两种解决方案。
-
Hibernate调用equals方法来检查对象是否已被更改,在此之前它调用deepCopy方法来获取自定义对象的副本。因此,在您的deepCopy方法中,创建自定义对象的新副本并实现equals方法正确。
Hibernate calls equals method to check whether object has been changed or not and before that it calls deepCopy method to get copy of custom object. So in your deepCopy method, create new copy of custom object and implement equals method correctly.
第二种解决方案是使用混合方法AccessType.FIELD和AccessType.PROPERTY。虽然不推荐这样做,但你可以看看它是否能让你知晓。
Second solution is using mix approach AccessType.FIELD and AccessType.PROPERTY. Although this is not recommended but u can see if it gives u knowledge.
这似乎与你的映射应该相似如下所示。
this seems as your mapping should be similar as below.
@Entity
@Table(name = TABLE_NAME)
@Entity@Table(name = TABLE_NAME)
@访问(AccessType.FIELD)
公共类EntityClass {
public class EntityClass {
/// ---一些字段
///---some fields
@Column(name =CustomCol)
@Column(name = "CustomCol")
@Type(type =com.something .CustomColType)
@Type(type = "com.something.CustomColType")
CustomClass customClass;
CustomClass customClass;
// - getters settters
//--getters settters
}
当您在ur类中拥有自定义对象并且只修改该对象时,它不会标记为脏对象。
解决方案1:使用customClass对象更新其他一些属性。
解决方案2:在customClass字段上输入 @Access(AccessType.PROPERTY),并为其提供getter / setter。
这将覆盖您在类级别上放置的默认AccessType.Field行为。
When you have custom object in ur class and you modify that object only then it doesn't mark as dirty.Solution 1 : update some other attribute with customClass object.Solution 2 : put @Access(AccessType.PROPERTY) on customClass field and provide getters/setters for same.This will override default AccessType.Field behavior that u put on class level.
如果您在课程级别上 @Access(AccessType.PROPERTY),则此问题将无法重现。
This issue will not be reproducible if you have @Access(AccessType.PROPERTY) on class level.
这篇关于具有自定义类型更改的Hibernate字段,但对象未标记为“脏”以进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!