多对多需要建立中间表
human表
job表
中间映射表
查询全部的人对应的工作
SELECT human.*,job.*
FROM human,job,humanjob
WHERE humanjob.jobID=job.id
and humanjob.humanID=human.id
我们以人为主体查询全部人所对应的多份工作
Human实体类
package com.lzm.pojo;
import java.util.List;
public class Human {
private Integer id;
private String name;
private Job job;
private List<Job> joblist;
public List<Job> getJoblist() {
return joblist;
}
public void setJoblist(List<Job> joblist) {
this.joblist = joblist;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
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 == null ? null : name.trim();
}
@Override
public String toString() {
return "Human{" +
"id=" + id +
", name='" + name + '\'' +
", job=" + job +
", joblist=" + joblist +
'}';
}
public Human() {
}
public Human(Integer id, String name, Job job, List<Job> joblist) {
this.id = id;
this.name = name;
this.job = job;
this.joblist = joblist;
}
}
Job实体类
package com.lzm.pojo;
public class Job {
private Integer id;
private String job;
private Human human;
@Override
public String toString() {
return "Job [id=" + id + ", job=" + job + ", human=" + human + "]";
}
public Human getHuman() {
return human;
}
public void setHuman(Human human) {
this.human = human;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job == null ? null : job.trim();
}
}
humanMapper文件
<resultMap id="BaseResultMap" type="com.lzm.pojo.Human" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<collection property="joblist" ofType="Job" >
<id column="id1" property="id" jdbcType="INTEGER" />
<result column="job" property="job" jdbcType="VARCHAR" />
</collection>
</resultMap>
<select id="selectAllHuamnJobByPrimaryKey" resultType="com.lzm.pojo.Human">
SELECT human.*,job.*
FROM human,job,humanjob
WHERE humanjob.jobID=job.id
and humanjob.humanID=human.id
</select>
HumanMapper接口添加
List<Human> selectAllHuamnJobByPrimaryKey();
//多对多 根据mapper文件的修改实现
@RequestMapping(value="/test6.action",method=RequestMethod.GET,produces = "text/json;charset=UTF-8")
@ResponseBody
public String test6()
{
List<Human> human = humanMapper.selectAllHuamnJobByPrimaryKey();
return human.toString();
}