cascade级联,只会影响CRUD的CUD,不会影响读取。不设置级联,从多的一方能读出一的一方,设了级联,从一的一方,默认也不能读出多的一方。
如果两个对象之间有关联,不管是一对多,多对一,单向还是双向,如果从A可以导向到B:
A--->B
默认情况下对A的保存不会影响到B,除非设cascade。如果A--->B--->C,从A能导航到B,B能导航到C,在B上也加上级联,对A的操作就能影响到C,但是,级联不是必须的,它只是让编程稍有方便。完全可以手动先存C,再存B,再存A.。
例子:Group类:
package com.oracle.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_group")//group是mysql的关键字,换个名 public class Group { 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; } }
User类:
package com.oracle.hibernate; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class User { private int id; private String name; private Group group; //多对一,级联。
@ManyToOne(cascade={CascadeType.ALL}) @JoinColumn(name="groupId")//指定外键名称 public Group getGroup() { return group; } public void setGroup(Group group) { this.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; } }
测试:
package com.oracle.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.AfterClass; import org.junit.BeforeClass; public class Test { private static SessionFactory sf = null; @BeforeClass public static void beforeClass(){ try { new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); sf = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @org.junit.Test public void testSchemaExport(){ new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); } @AfterClass public static void afterClass(){ sf.close(); } @org.junit.Test public void testSave(){ Session s = sf.getCurrentSession(); s.beginTransaction(); User user = new User(); user.setName("u1"); Group g = new Group(); g.setName("g1"); user.setGroup(g); //s.save(g);默认不会自动保存关联变量, //设置cascade后,直接保存user就能把user的group也保存 s.save(user); s.getTransaction().commit(); } }
数据库:
时间: 2024-12-29 04:27:45