hibernate中如何对一对多,多对一的单向关联进行级联的crud操作呢,主要使用cascade与fetch
例子如下:
首先是@OneToMany跟@ManyToOne中cascade属性的设置,查看hibernate annotation
文档可以看到cascade属性有几个取值,我们使用ALL来操作,cascade={CascadeType.ALL}
表示对级联的对象进行cud操作时候都进行级联操作(PS:进行读取操作的时候不级联),
进行读取操作的时候要设置fetch的属性,fetch=FetchType.EAGER,onetomany这方默认是LAZY,
manytoone这方默认是EAGER。
----------Group类如下:
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
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}
//fetch=FetchType.EAGER
)
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
---------------User类如下:
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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;
@ManyToOne(cascade={CascadeType.ALL})
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;
}
}
--------------hibernate.cfg.xml配置文件如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">heavenlin1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">update</property>
-->
<mapping class="com.bjsxt.hibernate.Group"/>
<mapping class="com.bjsxt.hibernate.User"/>
</session-factory>
</hibernate-configuration>
------------------测试类代码如下:
package com.bjsxt.hibernate;
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;
import org.junit.Test;
public class HibernateORMappingTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testSaveUser() {
User u = new User();
u.setName("u1");
Group g = new Group();
g.setName("g1");
u.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//s.save(g);
s.save(u);
s.getTransaction().commit();
}
@Test
public void testSaveGroup() {
User u1 = new User();
u1.setName("u1");
User u2 = new User();
u2.setName("u2");
Group g = new Group();
g.setName("g1");
g.getUsers().add(u1);
g.getUsers().add(u2);
u1.setGroup(g);
u2.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//s.save(g);
s.save(g);
s.getTransaction().commit();
}
@Test
public void testGetUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.get(User.class, 1);
System.out.println(u.getGroup().getName());
s.getTransaction().commit();
}
@Test
public void testLoadUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.load(User.class, 1);
System.out.println(u.getGroup().getName());
s.getTransaction().commit();
}
@Test
public void testDeleteUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//User u = (User)s.load(User.class, 1);
//u.setGroup(null);
//s.delete(u);
s.createQuery("delete from User u where u.id = 1").executeUpdate();
s.getTransaction().commit();
}
@Test
public void testDeleteGroup() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//User u = (User)s.load(User.class, 1);
//u.setGroup(null);
//s.delete(u);
Group g = (Group)s.load(Group.class, 1);
s.delete(g);
//s.createQuery("delete from User u where u.id = 1").executeUpdate();
s.getTransaction().commit();
}
@Test
public void testUpdateUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.get(User.class, 1);
s.getTransaction().commit();
u.setName("user");
u.getGroup().setName("group");
Session s2 = sessionFactory.getCurrentSession();
s2.beginTransaction();
s2.update(u);
s2.getTransaction().commit();
}
@Test
public void testGetGroup() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
Group g = (Group)s.get(Group.class, 1);
s.getTransaction().commit();
for(User u : g.getUsers()) {
System.out.println(u.getName());
}
}
@Test
public void testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
public static void main(String[] args) {
beforeClass();
}
}