resultMap的n+1方式实现多表查询(多对一)
实体类
创建班级类(Clazz)和学生类(Student),并在Student中添加一个Clazz类型的属性,用于表示学生的班级信息。
mapper层
提供studentMapper和ClazzMapper,studentMapper查询所有学生的信息,ClazzMapper根据 编号查询班级信息。再StudentMapper中使用<association>配置装配。
<association> 用于关联一个对象
- property:用于关联一个对象。
- select:设定要继续引用的查询,namespace+id
- column:查询时需要传递的列
service层
由于装配已经完成,serivce层只需调用mapper即可,不需要再进行装配了。
测试代码
多表关联查询_resultMap_单个对象_N+1方式实现
package com.bjsxt.mapper; import com.bjsxt.pojo.Clazz; public interface ClazzMapper { Clazz selById(int id);
}
package com.bjsxt.mapper; import java.util.List; import com.bjsxt.pojo.Student; public interface StudentMapper {
List<Student> selAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-|3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.ClazzMapper">
<select id="selById" resultType="clazz" parameterType="int">
select * from t_class where id=#{0}
</select> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-|3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.StudentMapper">
<resultMap type="student" id="smap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="gender" column="gender"/>
<result property="cid" column="cid"/>
<!-- 用于关联一个对象 -->
<association property="clazz" select="com.bjsxt.mapper.ClazzMapper.selById" column="cid"></association>
</resultMap>
<select id="selAll" resultMap="smap">
select * from t_student
</select> </mapper>
package com.bjsxt.pojo; import java.io.Serializable; public class Clazz implements Serializable{
private int id;
private String name;
private String room; public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((room == null) ? 0 : room.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Clazz other = (Clazz) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (room == null) {
if (other.room != null)
return false;
} else if (!room.equals(other.room))
return false;
return true;
}
public String toString() {
return "Clazz [id=" + id + ", name=" + name + ", room=" + room + "]";
}
public Clazz() {
super();
// TODO Auto-generated constructor stub
}
public Clazz(int id, String name, String room) {
super();
this.id = id;
this.name = name;
this.room = room;
}
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 String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
} }
package com.bjsxt.pojo; import java.io.Serializable; public class Student implements Serializable{
private int id;
private String name;
private int age;
private String gender;
private int cid;
private Clazz clazz;//用于封装班级信息
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + cid;
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (cid != other.cid)
return false;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", gender=" + gender + ", cid=" + cid + ", clazz=" + clazz + "]";
}
public Student(int id, String name, int age, String gender, int cid, Clazz clazz) {
super();
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.cid = cid;
this.clazz = clazz;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
} }
package com.bjsxt.service; import java.util.List; import com.bjsxt.pojo.Student; public interface StudentService {
List<Student> selAll(); }
package com.bjsxt.service.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.bjsxt.mapper.ClazzMapper;
import com.bjsxt.mapper.StudentMapper;
import com.bjsxt.pojo.Clazz;
import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.util.MyBatisUtil; public class StudentServiceImpl implements StudentService{ @Override
public List<Student> selAll() {
SqlSession session =MyBatisUtil.getSession(); StudentMapper stuMapper = session.getMapper(StudentMapper.class);
List<Student> list = stuMapper.selAll(); session.close();
return list;
} }
package com.bjsxt.test; import java.util.List; import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.impl.StudentServiceImpl; public class TestQuery { public static void main(String[] args) {
StudentService ss=new StudentServiceImpl();
List<Student> list = ss.selAll();
for (Student student : list) {
System.out.println(student);
} } }
package com.bjsxt.util; import java.io.IOException;
import java.io.InputStream; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static SqlSessionFactory factory=null;
static{ try {
InputStream is=Resources.getResourceAsStream("mybatis.xml");
factory=new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static SqlSession getSession(){
SqlSession session =null;
if(factory!=null){
//true表示开启
session= factory.openSession(true);
}
return session;
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java505?useSSL=true&characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=root
# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=ERROR, CONSOLE
# log4j.rootCategory=DEBUG, CONSOLE, LOGFILE # 单独设置SQL语句的输出级别为DEBUG级别
log4j.logger.com.bjsxt.mapper=DEBUG # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n # LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<!-- 设置MyBatis使用log4j日志支持 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- typeAliases给类型取别名 -->
<typeAliases>
<!-- 给user类取别名 -->
<!-- <typeAlias type="com.bjsxt.pojo.User" alias="u"/> -->
<!-- 别名都是类的名字 -->
<package name="com.bjsxt.pojo"/>
</typeAliases>
<!-- 用于指定使用哪个开发
用于指定使用的环境id
-->
<environments default="dev">
<!-- 用于配置开发环境
id:环境的唯一识别码
-->
<environment id="dev">
<!-- 事务管理器
type:用于设定mybatis采用什么方式管理事务
JDBC表示和JDBC一样事务的管理方式
-->
<transactionManager type="JDBC"/>
<!-- 数据源/连接池
用于配置链接池和数据库链接的参数
type:用于设置mybatis是否采用链接池技术
连接池:用来存数据库链接的,减少数据库的频繁开关
POOLED表示mybatis采用连接池技术
-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 扫描mapper文件 -->
<!-- 文件的全限制路径要用/ -->
<mappers>
<!-- <mapper class="com.bjsxt.mapper.UserMapper"/> -->
<package name="com.bjsxt.mapper"/> </mappers>
</configuration>
多表关联查询_resultMap_单个对象_关联方式实现
package com.bjsxt.mapper; import java.util.List; import com.bjsxt.pojo.Student; public interface StudentMapper { List<Student> selAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.StudentMapper">
<resultMap type="student" id="smap">
<id property="id" column="sid" />
<result property="name" column="sname" />
<result property="age" column="age" />
<result property="gender" column="gender" />
<result property="cid" column="cid" />
<association property="clazz" javaType="clazz">
<id property="id" column="cid" />
<result property="name" column="cname" />
<result property="room" column="room" />
</association>
</resultMap>
<select id="selAll" resultMap="smap">
select s.id sid, s.name sname, s.age, s.gender, c.id cid, c.name cname, c.room
from t_student s
left join t_class c
on s.cid=c.id
</select>
</mapper>
package com.bjsxt.pojo; import java.io.Serializable; public class Clazz implements Serializable { private int id;
private String name;
private String room; public Clazz() {
super();
} 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 String getRoom() {
return room;
} public void setRoom(String room) {
this.room = room;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((room == null) ? 0 : room.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Clazz other = (Clazz) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (room == null) {
if (other.room != null)
return false;
} else if (!room.equals(other.room))
return false;
return true;
} @Override
public String toString() {
return "Clazz [id=" + id + ", name=" + name + ", room=" + room + "]";
}
}
package com.bjsxt.pojo; import java.io.Serializable; public class Student implements Serializable { private int id;
private String name;
private int age;
private String gender;
private int cid;
private Clazz clazz;// 用于封装班级信息 public Student() {
super();
} 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public int getCid() {
return cid;
} public void setCid(int cid) {
this.cid = cid;
} public Clazz getClazz() {
return clazz;
} public void setClazz(Clazz clazz) {
this.clazz = clazz;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + cid;
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (cid != other.cid)
return false;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} @Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", cid=" + cid
+ ", clazz=" + clazz + "]";
}
}
package com.bjsxt.service; import java.util.List; import com.bjsxt.pojo.Student; public interface StudentService { List<Student> selAll();
}
package com.bjsxt.service.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.bjsxt.mapper.StudentMapper;
import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.util.MyBatisUtil; public class StudentServiceImpl implements StudentService { public List<Student> selAll() {
SqlSession session = MyBatisUtil.getSession(); // 学生mapper
StudentMapper stuMapper = session.getMapper(StudentMapper.class); List<Student> list = stuMapper.selAll(); session.close();
return list;
} }
package com.bjsxt.test; import java.util.List; import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.impl.StudentServiceImpl; public class TestQuery { public static void main(String[] args) {
StudentService ss = new StudentServiceImpl();
List<Student> list = ss.selAll();
for (Student student : list) {
System.out.println(student);
}
} }
package com.bjsxt.util; import java.io.IOException;
import java.io.InputStream; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static SqlSessionFactory factory = null; static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
} public static SqlSession getSession() {
SqlSession session = null;
if (factory != null) {
// true表示开启自动提交
// session = factory.openSession(true);
session = factory.openSession();
}
return session;
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java505
jdbc.username=root
jdbc.password=root
# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=ERROR, CONSOLE
# log4j.rootCategory=DEBUG, CONSOLE, LOGFILE # 单独设置SQL语句的输出级别为DEBUG级别
log4j.logger.com.bjsxt.mapper=DEBUG # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n # LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- properties加载外部文件 -->
<properties resource="db.properties" />
<!-- settings标签 -->
<settings>
<!-- 设置MyBatis使用log4j日志支持 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- typeAliases给类型起别名 -->
<typeAliases>
<package name="com.bjsxt.pojo" />
</typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.bjsxt.mapper" />
</mappers>
</configuration>