本文共 2154 字,大约阅读时间需要 7 分钟。
用户和组的关联,一个用户只能属于一个组,一个组可以拥有多个用户
User.java:
package cn.edu.hpu.one2many;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToOne;import javax.persistence.Table;@Entity@Table(name="m_user")public class User { private int id; private String name; private Group group; @ManyToOne public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @Id @GeneratedValue 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; } }Group.java:
package cn.edu.hpu.one2many;import java.util.HashSet;import java.util.Set;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="m_group")public class Group { private int id; private String name; private Set在hibernate.cfg.xml中添加: <mapping class="cn.edu.hpu.many2many.Group"/> <mapping class="cn.edu.hpu.many2many.User"/> 生成的sql语句: alter table m_user drop foreign key FKBF71E05DAB4F2BAC drop table if exists m_group drop table if exists m_user create table m_group ( id integer not null auto_increment, name varchar(255), primary key (id) ) create table m_user ( id integer not null auto_increment, name varchar(255), groupId integer, primary key (id) ) alter table m_user add index FKBF71E05DAB4F2BAC (groupId), add constraint FKBF71E05DAB4F2BAC foreign key (groupId)users=new HashSet (); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 @Id @GeneratedValue 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; } //只要有双向就要指定制定一个属性(mapedby) //不指定的话会有两个相同的字段产生 @OneToMany(mappedBy="group") public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; } }
references m_user (id)
转载请注明出处: