Many-to-many relationship mapping in hibernate

巴扎黑
Release: 2016-12-20 15:35:09
Original
1207 people have browsed it

Case:

person: One person can hold many jobs

job: One job can be held by many people

This forms a many-to-many relationship between person and job, which is mapped into a new table.

package com.pk.mapping;
import java.util.HashSet;
import java.util.Set;
public class Job {
private int id;
private String jobname;
private Set people=new HashSet();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getJobname() {
return jobname;
}
public void setJobname(String jobname) {
this.jobname = jobname;
}
public Set getPeople() {
return people;
}
public void setPeople(Set people) {
this.people = people;
}
}
Copy after login
package com.pk.mapping;
import java.util.HashSet;
import java.util.Set;
public class People {
private int id;
private String name;
private Set jobs=new HashSet();
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;
}
public Set getJobs() {
return jobs;
}
public void setJobs(Set jobs) {
this.jobs = jobs;
}
}
Copy after login
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pk.mapping">
<class name="Job" table="t_job">
<id name="id" column="t_job_id">
<generator class="native"></generator>
</id>
<property name="jobname" column="t_job_name"></property>
<set name="people" table="t_job_people" >
<!--外键,必须以本表的id作为参照物-->
<key column="job_id"></key>
<many-to-many class="People" column="people_id" />
</set>
</class>
</hibernate-mapping>
Copy after login
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pk.mapping">
<class name="People" table="t_people">
<id name="id" column="t_people_id">
<generator class="native"></generator>
</id>
<property name="name" column="t_people_name"></property>
<set name="jobs" table="t_job_people">
<key column="people_id"></key>
<many-to-many class="Job" column="job_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template