在继续Hibernate之前自动设置bean值(列)? [英] Setting a bean value (column) automatically before persisting in Hibernate?

查看:101
本文介绍了在继续Hibernate之前自动设置bean值(列)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Hibernate持久化实体之前,有没有一种很好且优雅的方式来设置bean值(列)?基本上我有一个名为modification_date的字段。它在一堆实体上。每当这些实体中的一个被更新/修改时,我基本上会自动设置该字段。



我可以在服务层编写代码来设置日期手动保存/更新对象...

我也有一个Dao Layer。每个Dao都从包含save()方法的支持类扩展而来。我可以使用反射并在此方法内设置值。我可以检查该类是否有名为modicationDate的字段,如果有,则将其设置为新的Date()。



是否有更好的比这更方式吗?或者使用我的通用save()方法是最好的方法?这是我想要强健的事情,不必再为此担心。我会很高兴知道,通过简单地制作一个修改日期属性,这将从这一点自动照顾我。使用save()方法看起来是最好的地方,但如果有更好的方法,我想知道它。 解决方案

结帐活动监听器

  @Entity 
@EntityListeners(class = LastUpdateListener.class)
公共类Cat {
@Id私人整数ID;
私人字符串名称;
私人日历dateOfBirth;
@Transient private int age;
私人日期lastUpdate;

@PostLoad
public void calculateAge(){
...
}
}

public class LastUpdateListener {
/ **
*任何数据库持久化之前设置的自动属性
* /
@PreUpdate
@PrePersist
public void setLastUpdate(Cat o){
o.setLastUpdate(new Date());
}
}


Is there a nice and elegant way to set a bean value (column) before Hibernate persists an entity? Basically I have a field called "modification_date". It's on a bunch of entities. Whenever one of these entities is updated/modified, I'd basically like that field set automatically.

I could write the code in the service layer to set the date every time the object is saved/updated manually...

I also have a Dao Layer. Every Dao extends from a support class that contains a save() method. I could just use reflection and set the value inside of this method. I could check to see if that class has a field with the name "modicationDate", and if it does, set it to new Date().

Is there a better way than this? Or is using my generic save() method the best approach? This is something I'd like to be robust and not have to worry about it ever again. I will be happy knowing that by simply making a "modificationDate" property that this will be taken care of for me automatically from this point on. Using the save() method seems like the best place, but if there's a better way, I'd like to become aware of it.

解决方案

Checkout event listeners:

@Entity
@EntityListeners(class=LastUpdateListener.class)
public class Cat {
    @Id private Integer id;
    private String name;
    private Calendar dateOfBirth;
    @Transient private int age;
    private Date lastUpdate;

    @PostLoad
    public void calculateAge() {
        ...
    }
}

public class LastUpdateListener {
    /**
     * automatic property set before any database persistence
     */
    @PreUpdate
    @PrePersist
    public void setLastUpdate(Cat o) {
        o.setLastUpdate( new Date() );
    }
}

这篇关于在继续Hibernate之前自动设置bean值(列)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆