Annotation版本:
Group类:
package com.hibernate.model;
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.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="_Group")
public class Group {
private int id;
private String name;
private Set<User> users = new HashSet<User>();
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@OneToMany(mappedBy="group")
//双向的必须写上mappedBy,而且在数据库方面考虑,关联关系应该设计在多的一方,所以必须在OneToMany这方设mappedBy
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public void setName(String name) {
this.name = name;
}
}
User类:
package com.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="_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;
}
}
配置文件以及测试用例请参考以前的文章
xml版本:
Group类,User类同上
User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.model">
<class name="User" table="_User">
<id name="id">
<generator class="native"/>
</id>
<property name="name"></property>
<many-to-one name="group" column="groupId"></many-to-one>
</class>
</hibernate-mapping>
Group.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.model">
<class name="Group" table="_Group">
<id name="id">
<generator class="native"/>
</id>
<property name="name"></property>
<set name="users">
<key column="groupId"></key>
<one-to-many class="com.hibernate.model.User"/>
</set>
</class>
</hibernate-mapping>
尊重版权,转载请注明本文链接
欢迎关注行者摩罗微信公众号(xingzhemoluo),共同交流编程经验,扫描下方二维码即可;