Hibernate 学习总计2
持久化三个要点:
1,为持久化字段声明访问器(accessors)和是否可变的标志(mutators)
属性不一定需要声明为public的。Hibernate可以对default,protected或者private的get/set方法对的属性一视同仁地执行持久化。
2,实现一个默认的构造方法(constructor)
所有的持久化类都必须具有一个默认的构造方法(可以不是public的),这样的话Hibernate就可以使用Constructor.newInstance()来实例化它们。
3,提供一个标识属性(identifier property)(可选)
这个属性可以叫任何名字,其类型可以是任何的原始类型、原始类型的包装类型、java.lang.String 或者是 java.util.Date。(如果你的老式数据库表有联合主 键,你甚至可以用一个用户自定义的类,其中每个属性都是这些类型之一。但该要求是可选的,一些功能只能对声明了标识属性的类起作用。
补充:
代理(proxies),要求持久化类不是final的,或者是一个全部方法都是public的接口的具体实现。你可以对一个final的,也没有实现接口的类执行持久化,但是不能对它们使用代理——多多少少会影响你进行性能优化的选择。session的load方法就是用到了代理。懒加载返回一个传递进来的类的子类的实体。
持久化生命周期(Lifecycle)中的回调(Callbacks)
作为一个可选的步骤,可持久化类可以实现Lifecycle接口,它可以提供一些用于回调的方法,可以让持久化对象在save或load之后,或者在delete或update之前进行必要的初始化与清除步骤。
//使用主键生成器为hilo时,打印输出1.如果改为native,则打印输出为0. //使用主键生成器为hilo时,打印输出1.如果改为native,则打印输出为0. Java代码 public class User implements Lifecycle { public boolean onDelete(Session arg0) throws CallbackException { throw new UnsupportedOperationException("Not supported yet."); } public void onLoad(Session arg0, Serializable arg1) { throw new UnsupportedOperationException("Not supported yet."); } public boolean onSave(Session arg0) { System.out.println("onSave!"); System.out.println(this.id); return true; //这里返回ture,导致保存操作被取消,检查数据库表,果然未插入成功。改为返回false,则插入记录成功。 } public boolean onUpdate(Session arg0) throws CallbackException { throw new UnsupportedOperationException("Not supported yet."); } private int id; private String userName; private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } public class User implements Lifecycle { public boolean onDelete(Session arg0) throws CallbackException { throw new UnsupportedOperationException("Not supported yet."); } public void onLoad(Session arg0, Serializable arg1) { throw new UnsupportedOperationException("Not supported yet."); } public boolean onSave(Session arg0) { System.out.println("onSave!"); System.out.println(this.id); return true; //这里返回ture,导致保存操作被取消,检查数据库表,果然未插入成功。改为返回false,则插入记录成功。 } public boolean onUpdate(Session arg0) throws CallbackException { throw new UnsupportedOperationException("Not supported yet."); } private int id; private String userName; private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }}