双向多对多
Posted -EASY-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了双向多对多相关的知识,希望对你有一定的参考价值。
1.在双方实体类里添加对方的集合
Emp实体类:
public class Emp { private Integer nid; private String empname; Set<Project> pros=new HashSet<Project>(); public Emp() { super(); } public Emp(Integer nid, String empname) { super(); this.nid = nid; this.empname = empname; } public Integer getNid() { return nid; } public void setNid(Integer nid) { this.nid = nid; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public Set<Project> getPros() { return pros; } public void setPros(Set<Project> pros) { this.pros = pros; } }
Project实体类:
public class Project { private int pid; private String pname; private Set<Emp> emps=new HashSet<Emp>(); public Project() { super(); } public Project(int pid, String pname) { super(); this.pid = pid; this.pname = pname; } public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } }
2.双向的多对多需要在双方的小配置里添加<set></set>元素 *需要加table属性*:
Emp.hbm.xml
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.a.happy"> <class name="Emp" table="EMP"> <id name="nid" column="nid"> <!-- native 数据库方言的可移植性 --> <generator class="native"></generator> </id> <property name="empname" type="string" column="empname"/> <!-- 多对多 --> <set name="pros" table="ProEmp" > <key column="nid"/> <!-- 在哪个配置,就写配置对应的主键 --> <many-to-many class="Project" column="pid"/> <!-- 对应多的一方成员类型 --> </set> </class> </hibernate-mapping>
Project.hbm.xml:
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.a.happy"> <class name="Project" table="PROJECT"> <id name="pid" column="pid"> <generator class="native"></generator> </id> <property name="pname" type="string" column="pname"/> <!-- 多对多 需要在<set>元素里 加一个table属性 table="生成第三张表的名字" --> <set name="emps" table="ProEmp" > <key column="pid"/> <!-- 在哪个配置,就写配置对应的主键 --> <many-to-many class="Emp" column="nid"/> <!-- 对应多的一方成员类型 --> </set> </class> </hibernate-mapping>
进行测试:
/** * 多对多双向关联测试 * 添加操作 */ @Test public void muchVsMuchTest(){ Emp emp1=new Emp(1,"李睿智"); Emp emp2=new Emp(2,"小明"); Project project1=new Project(1,"一号项目"); Project project2=new Project(2,"二号项目"); project1.getEmps().add(emp1); project1.getEmps().add(emp2); project2.getEmps().add(emp1); session.save(project1); session.save(project2); }
以上是关于双向多对多的主要内容,如果未能解决你的问题,请参考以下文章