MyBatis总结
1.接口代理方式实现规则
- 映射配置文件中的名称空间必须和Dao层接口的全类名相同
- 映射配置文件中的增删改查标签的id属性必须和Dao层接口的方法名相同
- 映射配置文件中的增删改查标签的parameterType属性和Dao层接口方法的参数相同
- 映射配置文件中的增删改查标签的resultType属性必须和Dao层接口方法的返回值相同
2.MybatisConfig.xml文件
<?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 核心根标签-->
<configuration>
<!--引入数据库连接的配置文件-->
<properties resource="jdbc.properties"/>
<!-- 配置log4j -->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 起别名 -->
<typeAliases>
<package name="com.an.pojo"/>
</typeAliases>
<!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
<environments default="mysql">
<!--environment配置数据库环境 id属性唯一标识-->
<environment id="mysql">
<!-- transactionManager事务管理。 type属性,采用JDBC默认的事务-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource数据源信息 type属性 连接池-->
<dataSource type="POOLED">
<!-- property获取数据库连接的配置信息 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- mappers引入映射配置文件 -->
<mappers>
<!-- mapper 引入指定的映射配置文件 resource属性指定映射配置文件的名称 -->
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
MybatisMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">
<!-- 查询所有 -->
<select id="selectAll" resultType="student">
SELECT * FROM student
</select>
<!-- 根据id查询 -->
<select id="selectById" resultType="com.an.pojo.Student" parameterType="int">
select * from student where id=#{id}
</select>
<!-- 添加 -->
<insert id="insert" parameterType="student">
INSERT INTO student(id,NAME,age) values (#{id},#{name},#{age})
</insert>
<!-- 修改 -->
<update id="update" parameterType="student">
update student set name=#{name},age=#{age} where id=#{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="int">
delete from student where id=#{id}
</delete>
</mapper>
3.实现流程
@Test
public void selectById() throws Exception{
//1.加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过工厂对象获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行映射配置文件中的sql语句,并接收结果
Student stu = sqlSession.selectOne("StudentMapper.selectById", 3);
//5.处理结果
System.out.println(stu);
//6.释放资源
sqlSession.close();
is.close();
}
4.起别名
<!-- 给pojo包下的所有类起别名 -->
<typeAliases>
<package name="com.an.pojo"/>
</typeAliases>
5.引入数据库连接的配置文件
<!--引入数据库连接的配置文件-->
<properties resource="jdbc.properties"/>
6.配置log4j
<!--
1.导入jar包
2.在mybatisConfig.xml文件中配置必须放在上边
3.在src目录下导入log4j的配置信息文件
-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
7.动态sql
-
标签
-
条件标签:如果有动态条件,则使用该标签代替where关键字
- 可以去除多余的and
-
条件判断标签:
-
and 字段=占位符(and id = #{id})
-
-
<!-- 多条件查询 对应的sql语句: select * from student where id = #{id} AND name = #{name} AND age = #{age} --> <select id="selectCondition" resultType="student" parameterType="student"> select * from student <where> <if test="id != null"> id = #{id} </if> <if test="name != null"> AND name = #{name} </if> <if test="age != null"> AND age = #{age} </if> </where> </select>
-
-
标签
-
获取参数(#{id})
-
属性:
- collection:参数容器类型,(list-集合,array-数组)
- open:开始的sql语句
- close:结束的sql语句
- item:参数变量名
- separator:分隔符
-
<!-- 根据多个id查询 对应的sql语句: select * from student where id in (1,2,3); --> <select id="selectByIds" resultType="student" parameterType="list"> select * from student <where> <foreach collection="list" open="id in (" close=")" item="id" separator=","> #{id} </foreach> </where> </select>
-
8.sql片段抽取
- 抽取一些重复的SQL语句(比如:select * from student)
- :抽取SQL语句标签
- 抽取的sql语句
- :引入SQL片段标签
9.分页插件
开发步骤:
-
导入PageHelper的jar包
- pagehelper-5.1.10.jar
- jsqlparser-3.1.jar
-
在mybatis核心配置文件中配置PageHelper插件
-
<plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins>
-
-
数据获取
@Test public void selectpaging() throws Exception { InputStream is = Resources.getResourceAsStream("MybatisConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = build.openSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //第一页显示三条 // PageHelper.startPage(1,3); //第二页显示三条 // PageHelper.startPage(2,3); // //第三页显示三条 // PageHelper.startPage(3,3); List<Student> list = mapper.selectAll(); for (Student student : list) { System.out.println(student); } sqlSession.close(); is.close(); }
-
获取分页相关参数
//获取分页相关参数 PageInfo<Student> info = new PageInfo<>(list); System.out.println("总条数:" + info.getTotal()); System.out.println("总页数:" + info.getPages()); System.out.println("当前页:" + info.getPageNum()); System.out.println("每页显示条数:" + info.getPageSize()); System.out.println("上一页:" + info.getPrePage()); System.out.println("下一页:" + info.getNextPage()); System.out.println("是否是第一页:" + info.isIsFirstPage()); System.out.println("是否是最后一页:" + info.isIsLastPage());
返回值 方法名 说明 long getTotal() 获取总条数 int getPages() 获取总页数 int getPageNum() 获取当前页 int getPageSize() 获取每页显示条数 int getPrePage() 获取上一页 int getNextPage() 获取下一页 boolean isIsFirstPage() 获取是否是第一页 boolean isIsLastPage() 获取是否是最后一页
10.多表操作
-
一对一
- 一个人对应一个身份证就是一对一
-
一对多
- 一个班级可以有多个学生就是一对多
-
多对多
- 多个学生可以选多种课,一种课也可以被多个学生选
-
一对一
-
:配置字段和对象属性的映射关系标签
- id属性:唯一表示
- type属性:实体对象类型
-
:配置主键映射关系标签
-
:配置主键映射关系标签
- column属性:表中的字段名称
- property属性:实体类中对应的变量名称
-
:配置被包含对象的映射关系标签
- Property属性:被包含对象的变量名
- JavaType属性:被包含对象的数据类型
-
//描述一对一 //身份证的类 public class Card { private Integer id; //主键id private String number; //身份证号 private Person p; //所属人的对象 // get/set.... 构造... toString... } //人的类 public class Person { private Integer id; //主键id private String name; //人的姓名 private Integer age; //人的年龄 // get/set.... 构造... toString... }
-
<!-- 一对一的Mapper.xml文件 --> <mapper namespace="com.an.table01.Ont_To_OneMapper"> <!--配置字段和实体对象属性的映射关系--> <resultMap id="oneToOne" type="com.an.pojo.Card"> <id column="cid" property="id"/> <result column="number" property="number"/> <!-- association:配置被包含对象的映射关系 property:被包含对象的变量名 javaType:被包含对象的数据类型 --> <association property="p" javaType="com.an.pojo.Person"> <id column="pid" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </association> </resultMap> <select id="selectAll" resultMap="oneToOne"> SELECT c.id cid,number,pid,name,age FROM card c,person p where c.pid = p.id </select> </mapper>
-
-
一对多
-
:配置字段和对象属性的映射关系标签
- id属性:唯一表示
- type属性:实体对象类型
-
:配置主键映射关系标签
-
:配置主键映射关系标签
- column属性:表中的字段名称
- property属性:实体类中对应的变量名称
-
:配置被包含集合对象的映射关系标签
- property属性:被包含集合对象的变量名
- ofType属性:集合中保存的对象数据类型
-
//学生类 public class Student { private Integer id; //主键id private String name; //学生姓名 private Integer age; //学生年龄 // get/set.... 构造... toString... } //班级类 public class Classes { private Integer id; //主键id private String name; //班级名称 private List<Student> students; //班级中所有学生对象 // get/set.... 构造... toString... }
-
<!-- 一对多的Mapper.xml文件 --> <mapper namespace="com.an.table02.OneToManyMapper"> <resultMap id="oneToMany" type="com.an.pojo.Classes"> <id column="cid" property="id"/> <result column="cname" property="name"/> <collection property="students" ofType="com.an.pojo.Student"> <id column="sid" property="id"/> <result column="sname" property="name"/> <result column="sage" property="age"/> </collection> </resultMap> <select id="selectAll" resultMap="oneToMany"> SELECT c.id cid,c.name cname,s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id = s.cid </select> </mapper>
-
-
多对多
-
和一对多基本一致
-
//课程类 public class Course { private Integer id; //主键id private String name; //课程名称 // get/set.... 构造... toString... } //学生类 public class Student { private Integer id; //主键id private String name; //学生姓名 private Integer age; //学生年龄 // get/set.... 构造... toString... }
-
<!-- Mapper.xml文件 --> <mapper namespace="com.itheima.table03.ManyToManyMapper"> <resultMap id="manyToMany" type="student"> <id column="sid" property="id"/> <result column="sname" property="name"/> <result column="sage" property="age"/> <collection property="courses" ofType="course"> <id column="cid" property="id"/> <result column="cname" property="name"/> </collection> </resultMap> <select id="selectAll" resultMap="manyToMany"> SELECT sc.sid,s.name sname,s.age sage,sc.cid,c.name cname FROM student s,course c,stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id </select> </mapper>
-
11.Mybatis注解开发
-
常用注解
-
@Select(“查询SQL语句”)
-
<!-- configxml文件的映射关系配置 --> <Mappers> <package name="接口所在的包"> </Mappers>
-
//Mapper接口 public interface StudentMapper { //根据id查询 @Select("SELECT * FROM student WHERE id=#{id}") public abstract Student selectAll(Integer id); }
-
//测试 public class Test01 { @Test public void selectAll() throws Exception{ //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student stu = mapper.selectById(1); //6.处理结果 System.out.println(student); //7.释放资源 sqlSession.close(); is.close(); } }
-
-
@Insert(“增加SQL语句”)
-
@Delete(“删除SQL语句”)
-
@Update(“删除SQL语句”)
-
12.注解多表操作
-
一对一
-
//人类 public class Person { private Integer id; //主键id private String name; //人的姓名 private Integer age; //人的年龄 //get/set } //卡类 public class Card { private Integer id; //主键id private String number; //身份证号 private Person p; //所属人的对象 //get/set }
-
public interface CardMapper { //查询全部 @Select("SELECT * FROM card") @Results({ @Result(column = "id",property = "id"), @Result(column = "number",property = "number"), @Result( property = "p", // 被包含对象的变量名 javaType = Person.class, // 被包含对象的实际数据类型 column = "pid", // 根据查询出的card表中的pid字段来查询person表 /* one、@One 一对一固定写法 select属性:指定调用哪个接口中的哪个方法 */ one = @One(select = "com.itheima.one_to_one.PersonMapper.selectById") ) }) public abstract List<Card> selectAll(); }
-
public interface PersonMapper { //根据id查询 @Select("SELECT * FROM person WHERE id=#{id}") public abstract Person selectById(Integer id); }
-
-
一对多
-
public class Student { private Integer id; //主键id private String name; //学生姓名 private Integer age; //学生年龄 //getset } public class Classes { private Integer id; //主键id private String name; //班级名称 private List<Student> students; //班级中所有学生对象 //getset }
-
public interface StudentMapper { //根据cid查询student表 @Select("SELECT * FROM student WHERE cid=#{cid}") public abstract List<Student> selectByCid(Integer cid); }
-
public interface ClassesMapper { //查询全部 @Select("SELECT * FROM classes") @Results({ @Result(column = "id",property = "id"), @Result(column = "name",property = "name"), @Result( property = "students", // 被包含对象的变量名 javaType = List.class, // 被包含对象的实际数据类型 column = "id", // 根据查询出的classes表的id字段来查询student表 /* many、@Many 一对多查询的固定写法 select属性:指定调用哪个接口中的哪个查询方法 */ many = @Many(select = "com.itheima.one_to_many.StudentMapper.selectByCid") ) }) public abstract List<Classes> selectAll(); }
-
-
多对多
-
public class Course { private Integer id; //主键id private String name; //课程名称 //getset } public class Student { private Integer id; //主键id private String name; //学生姓名 private Integer age; //学生年龄 //getset }
-
public interface CourseMapper { //根据学生id查询所选课程 @Select("SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}") public abstract List<Course> selectBySid(Integer id); }
-
public interface StudentMapper { //查询全部 @Select("SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id") @Results({ @Result(column = "id",property = "id"), @Result(column = "name",property = "name"), @Result(column = "age",property = "age"), @Result( property = "courses", // 被包含对象的变量名 javaType = List.class, // 被包含对象的实际数据类型 column = "id", // 根据查询出student表的id来作为关联条件,去查询中间表和课程表 /* many、@Many 一对多查询的固定写法 select属性:指定调用哪个接口中的哪个查询方法 */ many = @Many(select = "com.itheima.many_to_many.CourseMapper.selectBySid") ) }) public abstract List<Student> selectAll(); }
-
13.注解总结
- column: sql中的字段名
- property: 对应实体类中的属性名
- JavaType: 被包含对象的数据类型
- 一对一: one = @One(select=“抽象方法的路径”)
- 一对多&多对多: many = @Many(select=“抽象方法的路径”)