hibernate interceptor onsave方法,带有null Serializable id

时间:2014-09-03 09:01:42

标签: hibernate

我扩展了EmptyInterceptor,我想记录一个新创建的实体id。在onSave方法中,Serializable id为null,实体主键也为null。我们正在使用hbm文件映射pojo类和generator class =" identity"对于主键。

1 个答案:

答案 0 :(得分:3)

这是因为在保存实体之前将调用EmptyInterceptor

尝试使用postFlush,其中ID可用。

以下是Hibernate 4.3的一个小例子:

Entity Student.java

@Entity
public class Student {
    @Id
    @GeneratedValue
    private int id;
    private String name;
}

Interceptor class: LogInterceptor.java

public class LogInterceptor extends EmptyInterceptor {

    Session session;

    public void setSession(Session session) {
        this.session = session;
    }

    public boolean onSave(Object entity, Serializable id, Object[] state,
            String[] propertyNames, Type[] types) throws CallbackException {
        System.out.println("Entered onSave : class - " + entity.getClass());
        if (entity instanceof Student) {
            Student s = (Student) entity;
            System.out.println("class:" + entity.getClass() + " , id: "+s.getId());
        }
        return false;

    }

    public void postFlush(Iterator iterator) {
        System.out.println("Entered postFlush");
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if (obj instanceof Student) {
                Student s = (Student) obj;
                System.out.println("class:" + s.getClass() + " , id: "+s.getId());
            }
        }
    }

    public Session getSession() {
        return session;
    }
}

Code to test this:

Configuration configuration = new Configuration().setInterceptor( new LogInterceptor() );
            configuration.configure("hibernate.cfg.xml");
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            SessionFactory sessionFactory = configuration
                    .buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
        session.getTransaction().begin();

        Student s1 = new Student();
        s1.setName("Test");
        session.save(s1);
        session.getTransaction().commit();

Output:

Entered onSave : class - class Student
class:class Student , id: 1

Entered postFlush
class:class Student , id: 1

在我的示例中,我在onSave方法本身获得了ID。