Hibernate one to many 单向设置:
实体类:
Group_t
package com.sshcp.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
@Entity
public class Group_t {
private int id ;
private String name;
private Set<Member> members = new HashSet<Member>();
@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;
}
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="group_id") // 此处要加joincolumn 否则会生成第三张表
public Set<Member> getMembers() {
return members;
}
public void setMembers(Set<Member> members) {
this.members = members;
}
}
Member.java
package com.sshcp.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Member {
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;
}
}
设置类:
public void saveOnetoManySingle() {
// TODO Auto-generated method stub
Group_t gt = new Group_t();
Member member1 = new Member();
Member member2 = new Member();
gt.setName("组一");
member1.setName("成员一");
member2.setName("成员二");
gt.getMembers().add(member1);
gt.getMembers().add(member2);
this.getHibernateTemplate().save(gt);
}
代码运行结果:
Hibernate: insert into Group_t (name) values (?)
Hibernate: insert into Member (name) values (?)
Hibernate: insert into Member (name) values (?)
Hibernate: update Member set group_id=? where id=?
Hibernate: update Member set group_id=? where id=?