hibernate_1700_one2many_many2one_bi_crud(2)

package com.bit.hibernate;

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.OneToMany;
import javax.persistence.Table;

@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;
}

@OneToMany(mappedBy="group",cascade={CascadeType.ALL})
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}


}

----------------------------------------------------------------------------------


package com.bjsxt.hibernate;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


@Entity
@Table(name="t_user")
public class User {

private int id;
private String name;
private 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;
}

@ManyToOne
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}



}

----------------------------------------------------------------------------------


package com.bjsxt.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();

Group group = new Group();
group.setName("g1");
User u1 = new User();
u1.setGroup(group); //要设置
u1.setName("u1");
User u2 = new User();
u2.setName("u2"); //要设置
u2.setGroup(group);

group.getUsers().add(u1);
group.getUsers().add(u2);
session.beginTransaction();
session.save(group);
session.getTransaction().commit();

}

}

一定要设置User到Group的导航
级联操作 保存group自动保存User

你可能感兴趣的:(Hibernate)