1、一對一相對比較簡單。hibernate主要是協助我們保持了兩張表的id一致!
先建兩張表
create table h_01.idcard (id integer not null, num integer, primary key (id));create table h_01.student (id integer not null, name varchar(255), primary key (id));
然後是POJO
package modle;public class IdCard {private int id;private int num;private Student student;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}}
package modle;public class Student {private int id;private String name;private IdCard idCard;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public IdCard getIdCard() {return idCard;}public void setIdCard(IdCard idCard) {this.idCard = idCard;}}
然後是對應檔:
重要的是這個地方:
<generator class="foreign">
<param name="property">student</param>
</generator>
表示IdCard的id是根據student的id產生的。 generator就是定義id的產生方式。 param是定義有那個屬性,即student來確定id.
<hibernate-mapping> <class name="modle.IdCard" table="idcard" catalog="h_01"> <id name="id" type="int"> <generator class="foreign"> <param name="property">student</param> </generator> </id> <property name="num" type="int"></property> <one-to-one name="student" class="modle.Student" fetch="select" ></one-to-one> </class></hibernate-mapping>
再說下查詢:
1、一對一,hibernate預設的是用左外串連查詢。
比如,查詢一個student, hibernate使用做外串連直接查詢除了idcard.
Hibernate: select student0_.id as id3_2_, student0_.name as name3_2_, idcard1_.id as id4_0_, idcard1_.num as num4_0_, student2_.id as id3_1_, student2_.name as name3_1_ from h_01.student student0_ left outer join h_01.idcard idcard1_ on student0_.id=idcard1_.id left outer join h_01.student student2_ on idcard1_.id=student2_.id where student0_.id=?
有事我們並不需要idcard,為了速度 。 可以用消極式載入。
需要修改下查詢方式,即fetch屬性的配置,預設是join
<one-to-one name="student" class="modle.Student" fetch="select" ></one-to-one>
注意:兩個設定檔都要修改!
這下查詢就變成了:
Hibernate: select student0_.id as id3_0_, student0_.name as name3_0_ from h_01.student student0_ where student0_.id=?Hibernate: select idcard0_.id as id4_0_, idcard0_.num as num4_0_ from h_01.idcard idcard0_ where idcard0_.id=?
之所以有兩個查詢語句,因為我使用了card對象。所以又查詢了card
2、預設對student的儲存是不級聯的。不知道是不是和版本有關。
可以把student配置設定為級聯的。