本文主要是介绍学MyBatis看这四篇就够了!(4)之一对多,多对一,分页查询以及Log4j的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MyBatis入门(4)
多对一查询第二种方法
首先,我们可以在sql上下个功夫:
select s.id sid,s.name sname,s.tid,t.name tname
from student s,teacher t
where s.tid=t.id
查询到的结果就是上面的,我们所希望的也是上面的形式,其实本质上也是个连接查询
更新StudentMapper.java,增加方法:
package com.lwh.dao;import com.lwh.pojo.Student;
import java.util.List;public interface StudentMapper {List<Student> selectAll();//较为简单的查询方法List<Student> selectAll2();
}
更新StudentMapper.xml:
<select id="selectAll2" resultMap="StudentTeacher2">select s.id sid,s.name sname,s.tid,t.name tname from student s,teacher t where s.tid=t.id
</select><resultMap id="StudentTeacher2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/></association>
</resultMap>
解析:
其实,不过就是把sql语句搬过来,再对Teacher对象进行根据id查询,首先看见id是selectAll2执行的sql语句,查询出来的字段有sid,sname,tid,tname这四个,所以在resultMap中有四个result的小标签,但是tid,tname其实是Teacher中的id和name属性,所以在student中的Teacher字段时需要用到association的标签进行对象包裹,里面的两个字段就是id和name,分别对应sql查询结果的tid和tname。
编写测试类:
@Test
public void testStudent2(){SqlSession sqlSession = MybatisUtils.getSqlSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);List<Student> list = mapper.selectAll2();for (Student student:list) {System.out.println(student);}sqlSession.close();
}
运行结果:
一对多查询
创建子项目
Student:
package com.lwh.pojo;public class Student {private int id;private String name;private int tid;public int getId() {return id;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", tid=" + tid +'}';}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getTid() {return tid;}public void setTid(int tid) {this.tid = tid;}
}
Teacher:
由于一个老师可以教很多个学生,所以老师对应的属性学生中是一个泛型为Student的list,属于一对多的关系
package com.lwh.pojo;import java.util.List;public class Teacher {private int id;private String name;private List<Student> students;@Overridepublic String toString() {return "Teacher{" +"id=" + id +", name='" + name + '\'' +", students=" + students +'}';}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 List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}
}
编写Dao层:
根据id来查询老师信息
package com.lwh.dao;import com.lwh.pojo.Teacher;
import org.apache.ibatis.annotations.Param;public interface TeacherMapper {Teacher selectById(@Param("tid") int id);
}
编写TeacherMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lwh.dao.TeacherMapper"><select id="selectById" resultMap="TeacherStudent">select s.id sid,s.name sname,s.tid,t.name tname from student s,teacher t where s.tid=t.id and t.id=#{tid}</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><collection property="students" ofType="student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection></resultMap>
</mapper>
解析:
- sql语句和上一个多对一的例子差不多,只不过加了一个根据tid来查询老师的信息
- 同样需要用到reslutMap来表示这样的多对一的关系
- 我们要得到的是Teacher对象,所以resultMap中type是Teacher
- 里面共有三个字段,一个是老师的id,一个是老师的名字,对应关系是property对应对象的属性名,column对应的是查询到的字段名
- 其中由于是一对多的关系,所以需要用到collection标签,对应到的属性名是students,但是类型因为是list,并且泛型为student,所以不能用javatype,只能用oftype,所以oftype中给到的是student
- 在collection中的字段就是属于学生的字段了,分别是id,name,tid,就不做过多赘述
编写测试类
@Testpublic void test2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.selectById(1); System.out.println(teacher); sqlSession.close();}
运行
成功!
分页查询
更新StudentMapper.java:
package com.lwh.dao;import com.lwh.pojo.Student;
import org.apache.ibatis.annotations.Select;import java.util.List;
import java.util.Map;public interface StudentMapper {@Select("select * from student")List<Student> selectAll();//分页查询方法List<Student> getUserByLimit(Map<String,Object> map);
}
更新StudentMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lwh.dao.StudentMapper">
<select id="getUserByLimit" parameterType="map" resultType="Student">select * from student limit #{startIndex},#{pageSize}
</select></mapper>
编写测试类
/*** 分页测试*/
@Test
public void test3(){SqlSession sqlSession = MybatisUtils.getSqlSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);//startIndex是分页的页数,pageSize是每页所显示的记录数HashMap<String, Object> hashMap = new HashMap<>();hashMap.put("startIndex",1);hashMap.put("pageSize",2);List<Student> list = mapper.getUserByLimit(hashMap);for (Student student:list){System.out.println(student);}sqlSession.close();}
由于实现比较简单,就不做一一赘述
使用Log4j打印日志
使用maven引入依赖
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
绑定log4j配置文件
在resources文件下创建log4j.properties文件,写入
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/lwh.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
测试类中进行绑定
static Logger logger=Logger.getLogger(test.class);
可以看到每次运行控制台都会输出一串字符
preparing显示的是执行的sql语句
parameters显示的是占位符做的参数
total显示的值是查询到的总记录数
这篇关于学MyBatis看这四篇就够了!(4)之一对多,多对一,分页查询以及Log4j的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!