一对多,双向,"一"的一方
package com.pegasus.domain; 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; //在实体类的类名前 //标注是实体 //对应的表名 //相当于xml的 //<class name="com.pegasus.domain.Group" table="t_group"></class> @Entity @Table(name="t_group") public class Group { private int id; private String name; private Set<User> users = new HashSet<User>(); //在主键的get方法前 //标注主键,以及生成主键策略 //相当于<id name="id"><generator class="native"></generator></id> @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } //在一般属性的get方法前 //一般的列名前不需要标注 //相当于<property name="name"></property> public String getName() { return name; } public void setName(String name) { this.name = name; } //在一对多"一"的一方关联的集合前 //使用@OneToMany标注,并标明"mappedBy",即关联的"多"的一方所对应的类的属性 //cascade参数标明级联的方式,如果不需要级联可以省略 //相当于<set name="users"> // <key column="groupId"></key> // <one-to-many class="com.pegasus.domain.User"/> // </set> @OneToMany(mappedBy="group", cascade={CascadeType.ALL} ) public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
一对多,双向,"多"的一方
package com.pegasus.domain; 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; //在实体类的类名前 //标注是实体 //对应的表名 //相当于xml的 //<class name="com.pegasus.domain.User" table="t_user"></class> @Entity @Table(name="t_user") public class User { private int id; private String name; private Group group; //在主键的get方法前 //标注主键,以及生成主键策略 //相当于<id name="id"><generator class="native"></generator></id> @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } //在一般属性的get方法前 //一般的列名前不需要标注 //相当于<property name="name"></property> public String getName() { return name; } public void setName(String name) { this.name = name; } //在一对多"多"的一方关联的属性get方法前 //使用@ManyToOne标注 //cascade参数标明级联的方式,如果不需要级联可以省略 //相当于<many-to-one name="group" column="groupId"></many-to-one> @ManyToOne(cascade={CascadeType.ALL}) public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } }
单元测试类
package com.pegasus.domain; 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() { System.out.print("begin to 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() { // System.out.print("begin to 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.getTransaction().commit(); // } /**级联查询*/ @Test public void testGetUser() { System.out.print("begin to testGetUser()"); // testSaveGroup(); Session s = sessionFactory.getCurrentSession(); s.beginTransaction(); User u = (User)s.get(User.class, 1); s.getTransaction().commit(); System.out.println(u.getGroup().getName()); } // @Test // public void testDeleteUser() { // System.out.print("begin to 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 testUpdateUser() { System.out.print("begin to 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 testDeleteGroup() { System.out.print("begin to 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 testSchemaExport() { // new SchemaExport(new AnnotationConfiguration().configure()).create(true, true); // } // public static void main(String[] args) { // beforeClass(); // } }
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/hibtest</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</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 resource="com/pegasus/domain/Group.hbm.xml"/> <mapping resource="com/pegasus/domain/User.hbm.xml"/> --> <mapping class="com.pegasus.domain.Group"/> <mapping class="com.pegasus.domain.User"/> </session-factory> </hibernate-configuration>