Hibernate关系映射(N--1和 1--N)多对一和一对多
注意 :尽量使用多对一,一对多关系效率有些慢
?
(1)N--1(单向N--1外键映射) 只要是外键,就会牵扯到多对一的关系
第一步:类、对象之间的关系映射
public class Room {
??? private int id;
??? private String roomName;??
}
?
public class User {
??? private int id;
??? private String truename;
???? private Room room;?
}
?
第二步:xml之间的映射
??? <class name="Room" table="t_room">
??? ??? <id name="id" column="room_id">
??? ??? ??? <generator unique="true" not-null="true" column="room_name" length="32"/>
??? </class>
?
<class name="User" table="t_user">
??? ??? <id name="id" column="id">
??? ??? ??? <generator unique="true" not-null="true" column="truename" length="32"/>
???? ???
??? ??? <many-to-one name="room" not-null="true" column="room_id" --外键
??????????? cascade="save-update">??? --保存修改级联
??????? </many-to-one>
??? </class>
?
第三步:创建对象
??? ??? Room room = new Room();
??? ???? room.setRoomName("听雨轩");
??? ??? ??
??? ??? ??? User u1 = new User();
??? ??? ??? u1.setTruename("张三");
??? ??? ??? u1.setRoom(room);
??? ??? ???
??? ??? ??? User u2 = new User();
??? ??? ??? u2.setTruename("李四");
??? ??? ??? u2.setRoom(room);
??? ??? ???
??? ??? ??? session.save(u1);
??? ??? ??? session.save(u2);
?
?
第四步:查询
??????? User user= (User )session.load(User .class, 1);
??????? Room room = user.getRoom();
??????? System.out.println(user.getTruename());
? ? ? ? System.out.println(room .getRoomName());
?
?
(2)N--1(双向N--1) 数据库和(1)中的相同
?
第一步:类、对象之间的关系映射
public class Room {
??? private int id;
??? private String roomName;??
??? private Set<User> users;? // 增加了user集合 但是数据库没有变化
}
?
public class User {
??? private int id;
??? private String truename;
???? private Room room;?
}
?
第二步:xml之间的映射
??? <class name="User" table="t_user">
??? ??? <id name="id" column="id">
??? ??? ??? <generator unique="true" not-null="true" column="truename" length="32"/>
??????? ???
??? ??? <many-to-one name="room" not-null="true" column="room_id"
???????? cascade="save-update"></many-to-one>
????? </class>
?
?
??? <class name="Room" table="t_room">
??? ??? <id name="id" column="room_id">
??? ??? ??? <generator unique="true" not-null="true" column="room_name" length="32"/>
??? ??? --增加了set的配置
??? ??? <set name="users">
??? ??? ??? <key column="room_id"></key>? --参考user中room_id字段
??? ??? ??? <one-to-many table="t_user">
??? ??? <id name="id" column="id">
??? ??? ??? <generator unique="true" not-null="true" column="truename" length="32"/>
???? </class>
?
?
<class name="Room" table="t_room">
??? ??? <id name="id" column="room_id">
??? ??? ??? <generator unique="true" not-null="true" column="room_name" length="32"/>
??? ???
??? ??? <set name="users" cascade="save-update"
????????????? inverse="true"> ?? ---反转,将主控关系交给对方来管理 (默认是false,代表由本身来维护)
??? ??? ??? <key column="room_id"></key>
??? ??? ??? <one-to-many class="User"/>
??? ??? </set>
??? ???
??? </class>
?
?
? 在N--1或者1--N双向关系维护(创建对象时候),强制交给多的一方进行维护,不让1的一方维护,这样能提高效率 , 减少了n条update语句,但是,在查询的时候, 在1的一方就不能查询关联数据了
?
? 注意 :尽量使用多对一,一对多关系效率有些慢
?
?