首页 > 代码库 > 双向多对多
双向多对多
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); }
双向多对多
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。