一对多单向关联
数据库表设计:在多方加外键
( @OneToMany
@JoinColumn(name = “groupId”) ,要写@JoinColumn否则hibernate认为是多对多,会生成3张表)
(
@Entity
@Table(name = "t_group")
public class Group {
private int id;
private String name;
private Set<User> user = new HashSet<User>();
@OneToMany
@JoinColumn(name = "groupId")
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
@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;
}
}
@Entity
@Table(name = "t_user")
public class User {
private int id;
private String name;
@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方式:
<hibernate-mapping package="hibernate">
<!--table 属性不配就是默认-->
<class name="Group" table="t_group">
<id name="id" >
<generator class="native"/>
</id>
<property name="name" column="name"/>
<set name="users">
<key column="groupId"></key>
<one-to-many class="hibernate.User"/>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping package="hibernate">
<!--table 属性不配就是默认-->
<class name="User" table="t_user">
<id name="id" >
<generator class="native"/>
</id>
<property name="name" column="name"/>
</class>
</hibernate-mapping>