一对多单向关联
@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>
<class name="com.bjsxt.hibernate.User" table="t_user">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
@Entity
@Table(name="t_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;
}
public void setName(String name) {
this.name = name;
}
在一的这一端Group端users属性上进行注解配置
@OneToMany //一对多关联 Group是一的一方 User是多的一方
@JoinColumn(name="groupId")
//指定User表中生成与Group对应的字段名注意此处与多对一配置方式不同
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
或者xml
<hibernate-mapping>
<class name="com.bjsxt.hibernate.Group" table="t_group">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<set name="users">
<key column="groupId"></key>
<one-to-many class="com.bjsxt.hibernate.User"/>
</set>
</class>
</hibernate-mapping>
User u=new User();
u.setName("u");
User u2=new User();
u2.setName("u2");
Group g=new Group();
g.setName("g");
Set<User> users=new HashSet<User>();
users.add(u);
users.add(u2);
g.setUsers(users);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(u);
session.save(u2);
session.save(g);
session.getTransaction().commit();
Hibernate: insert into t_user (name) values (?)
Hibernate: insert into t_user (name) values (?)
Hibernate: insert into t_group (name) values (?)
Hibernate: update t_user set groupId=? where id=?
Hibernate: update t_user set groupId=? where id=?