假设有User和groubs两个对象(表),当修改其中一个则另外一个也跟着改变。
package hibernate002test.copy;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
* cascade:集成
* @author Lenovo
*
*/
@Entity
public class User {
private int userid;
private String username;
private Groups group;
@ManyToOne(cascade= {CascadeType.ALL})//让Groups和User之间相互集成,all代表任何时候都相互影响
public Groups getGroup() {
return group;
}
public void setGroup(Groups group) {
this.group = group;
}
@Id
@GeneratedValue
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
package hibernate002test.copy;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Groups {
private int id;
private String name;
private Set<User>
user = new HashSet<User>
();
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToMany(mappedBy="group")
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package datatest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import hibernate002test.copy.Groups;
import hibernate002test.copy.User;
/**
* 在一对一双向关联时要使用例如:@OneToOne(mappedBy=”wife”)
*
* @author Lenovo
*
*/
public class Test {
private static SessionFactory sessionfactory;
@Before
public void Init() {
//new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);创建表
sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@After
public void Destroy() {
sessionfactory.close();
}
@org.junit.Test
public void test() {
User user=new User();
user.setUsername("貔貅");
Groups groups=new Groups();
groups.setName("饕餮");
user.setGroup(groups);
Session session=sessionfactory.getCurrentSession();
session.beginTransaction();
// session.save(groups);在User中使用了 cascade:集成
session.save(user);
session.getTransaction().commit();
}
}