分别创建user,farm,user_general三张表
create table user( uuid bigint not null auto_increment, name varchar(100), age int not null, province varchar(100), city varchar(100), street varchar(100), constraint pk_user primary key(uuid))charset=utf8 ENGINE=InnoDB;create table user_general(uuid bigint not null,realname varchar(10),gender varchar(10),birthday int,height int,weight int, constraint pk_user_general primary key(uuid), constraint fk_user_general foreign key(uuid) references user(uuid))charset=utf8 ENGINE=InnoDB;create table farm(uuid bigint not null auto_increment,user_id bigint,name varchar(10),constraint pk_farm primary key(uuid),constraint fk_farm foreign key(user_id) references user(uuid))charset=utf8 ENGINE=InnoDB;
单向关联:
1.多对一映射(many to one):
该标签在持久化类中属于多的一方配置;例如本例中farm即为多的一方。
重点是这段配置:
<many-to-one name="user" class="org.hibernate.tutorials.domain.User" column="user_id" cascade="save-update"/>
其中column对应表中的外键(另一张表的主键),cascade设置为save-update后即可实现向数据库中级联修改
farm.hbm.xml配置:
12 3 94 65 7 8
Farm对应的实体类:
public class Farm implements Serializable{ private int uuid; private String name; private User user;//农场所属用户 /** * @return the uuid */ public int getUuid() { return uuid; } /** * @param uuid the uuid to set */ public void setUuid(int uuid) { this.uuid = uuid; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the user */ public User getUser() { return user; } /** * @param user the user to set */ public void setUser(User user) { this.user = user; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Farm [uuid=" + uuid + ", name=" + name + "]"; }
测试代码:
1 Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 2 3 User user = new User(); 4 user.setName("lucy"); 5 6 Farm farm=new Farm(); 7 farm.setName("test3"); 8 farm.setUser(user); 9 10 Farm farm1=new Farm();11 farm1.setName("test4");12 farm1.setUser(user);13 14 session.beginTransaction();15 session.save(farm);16 session.save(farm1);17 session.getTransaction().commit();
2.一对一映射(分为2种情况:唯一外键和主键关联)
2.1:唯一外键:用的标签仍为many-to-one 区别是需要加unique="true"属性表示唯一映射,具体案例
2.2主键关联映射:(一个字段同时是主键和外键(user和user_general))
<one-to-one name="user" class="org.hibernate.tutorials.domain.User" constrained="true"/> constrained="true"指明该类(UserGeneral)和关联的类(User)对应的表,通过外键引用对主键约束
UserGeneral.hbm.xml 配置
12 3 114 85 user 6 79 10
测试代码:
1 Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 2 3 User user = new User(); 4 user.setName("rrrrr"); 5 6 UserGeneral ge=new UserGeneral(); 7 ge.setUser(user); 8 ge.setRealname("cccccc"); 9 10 session.beginTransaction();11 session.save(ge);12 session.getTransaction().commit();
参考:,