hibernate 多对多注解配置
1、在公司一个员工对应多个部门,一个部门对应多个员工,因此部门与员工之间就是多对多的关系。
Person类的代码如下:
package com.mr.cheng.bean; 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.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import org.hibernate.annotations.Cascade; @Entity public class Person { private Integer id; private String name; private int age; private double price; private Set<Dept> depts; /** * 多对多由一方来完成, */ @ManyToMany(cascade=CascadeType.ALL) @JoinTable(name="personDeptTable", /** * 这一方的Id */ joinColumns={@JoinColumn(name="personId")}, /** * 反转的另外一段的列名,既对方一张表的Id * @return */ inverseJoinColumns={@JoinColumn(name="deptId")} ) public Set<Dept> getDepts() { return depts; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", price=" + price + ", depts=" + depts + "]"; } public void setDepts(Set<Dept> depts) { this.depts = depts; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
Dept类的代码如下:
package com.mr.cheng.bean; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="deptTable") public class Dept { private int id; private String name; private Set<Person>persons; @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; } @ManyToMany (mappedBy="depts") public Set<Person> getPersons() { return persons; } public void setPersons(Set<Person> persons) { this.persons = persons; } }
2、hibernate.hbm.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/test </property> <property name="connection.username">root</property> <property name="connection.password">root</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> <mapping class="com.mr.cheng.bean.Dept" /> <mapping class="com.mr.cheng.bean.Person" /> </session-factory> </hibernate-configuration>
3、测试代码如下:
package com.mr.cheng.test; import java.util.Date; import java.util.HashSet; import org.hibernate.Query; 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; import com.mr.cheng.bean.Dept; import com.mr.cheng.bean.Person; public class HibernateTest { private static SessionFactory sessionFactory; //@BeforeClass public static void beforeClass() { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } //@AfterClass public static void afterClass() { sessionFactory.close(); } @Test public void testSchemaExport() { new SchemaExport(new AnnotationConfiguration().configure()).create(true, true); } public static void main(String[] args) { beforeClass(); } /** * 多对多单向 */ @Test public void testManyToManyAddPersonAndDept(){ new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Dept dept = new Dept(); dept.setName("财务部"); Dept dept1 = new Dept(); dept1.setName("财务部"); Person person = new Person(); person.setName("A111"); person.setAge(33); person.setPrice(33); Person person1 = new Person(); person1.setName("A111"); person1.setAge(33); person1.setPrice(33); person.setDepts(new HashSet<Dept>()); person1.setDepts(new HashSet<Dept>()); person.getDepts().add(dept); person.getDepts().add(dept1); person1.getDepts().add(dept); person1.getDepts().add(dept1); session.save(person1); session.save(person); /*session.save(dept1); session.save(dept);*/ session.getTransaction().commit(); } /** * 多对多单向查询 Person 一方 */ @Test public void testManyToManyQueryPerson(){ new SchemaExport(new AnnotationConfiguration().configure()).create(false, false); sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Person p = (Person) session.load(Person.class, 1); System.out.println(p.getDepts()); session.getTransaction().commit(); } /** * 多对多单向查询 Dept 一方 */ @Test public void testManyToManyQueryDept(){ new SchemaExport(new AnnotationConfiguration().configure()).create(false, false); sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Dept dept = (Dept) session.load(Dept.class, 1); System.out.println(dept.getPersons()); session.getTransaction().commit(); } @Test public void testManyToManyAddPersonAndDept1(){ sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Dept dept = new Dept(); dept.setName("财务部"); Dept dept1 = new Dept(); dept1.setName("财务部"); Person person = new Person(); person.setName("A111"); person.setAge(33); person.setPrice(33); Person person1 = new Person(); person1.setName("A111"); person1.setAge(33); person1.setPrice(33); dept1.setPersons(new HashSet()); dept.setPersons(new HashSet()); dept1.getPersons().add(person1); dept1.getPersons().add(person); /* session.save(person1); session.save(person);*/ session.save(dept1); session.save(dept); session.getTransaction().commit(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。