Mybatis学习笔记
简介
MyBatis是一个持久层的框架,简化jdbc代码以及参数设置和结果集映射。
介绍
使用方法:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
Session
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
//应能从文件名跳转到文件
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSession() throws IOException {
return sqlSessionFactory.openSession();
}
}
- SqlSessionFactory
每个基于MyBatis的应用都是以一个SqlSessionFactory实例为核心。一个SqlSessionFactory运行期间一直存在且无需创建第二个。
使用XML构建SqlSessionFactory实例,java方式看官方文档 。 - SqlSessionFactoryBuilder
仅在创建SqlSessionFactory时使用一次。 - Session
一个线程一个Session,Session不是线程安全的。
MyBatis核心配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册!!!-->
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
映射器
编写映射接口
public interface UserMapper {
List<User> getUserList();
}
编写映射接口的配置文件,配置文件相当于接口的实现类
<?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.ma.dao.UserMapper">
<select id="getUserList" resultType="User">
select * from user;
</select>
</mapper>
测试
public class UserMapperTest {
@Test
public void test1(){
//获取SqlSession
SqlSession sqlSession= MyBatisUtil.getSession();
//执行sql
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
List<User> userList=userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭Session
sqlSession.close();
}
}
命名空间
命名空间的作用有两个,一个是利用更长的全限定名来将不同的语句隔离开来,同时也实现了你上面见到的接口绑定。
依赖注入(DI)
DI指A中有B,传统是在A中new一个B,现在控制反(IOC),让他人new一个B给自己用(注入),这个B还可以给其他人用。
xml配置
顶层结构
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
properties
将一些配置放置外部,进行动态替换,如数据库连接datasource
settings
类型别名(typeAliases)
<typeAliases>
<typeAlias alias="user" type="com.ma.pojo.User"/>
<package name="com.ma.pojo"/>
</typeAliases>
一些java类型内建的类型别名如int、byte见官方文档
typeHandlers
参数或结果集转换类Java bean
环境配置(environments)
- 默认使用的环境 ID(比如:default="development")。
- 每个 environment 元素定义的环境 ID(比如:id="development")。
- 事务管理器的配置(比如:type="JDBC")。
- 数据源的配置(比如:type="POOLED")。
- 事务管理器(transactionManager),如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置。
映射器(mappers)
建议使用xml文件,使用class或package导入mapper.xml会出现一些问题,如接口个mapper.xml要在一个文件夹下。
XML映射文件
- cache – 该命名空间的缓存配置。
- cache-ref – 引用其它命名空间的缓存配置。
- resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
- sql – 可被其它语句引用的可重用语句块。
- insert – 映射插入语句。
- update – 映射更新语句。
- delete – 映射删除语句。
- select – 映射查询语句。
每个元素内的属性都极其重要。官方文档
select
- resultMap。
对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。- constructor属性
MyBatis在将数据转为java bean时用到的构造方法。MyBatis也支持set构造。
若java bean与数据库中字段名不一致,则查询不出,解决办法: - 起别名:
select id,name,pwd as password from user;
- resultmap方式
事实上即使没有使用resultMap而是用resultType,MyBatis也会在幕后自动创建一个resultMap。<resultMap id="UserMap" type="user"> <result column="pwd" property="pwd"/> </resultMap> <select id="getUserById" parameterType="int" resultMap="UserMap"> select * from user where id=#{id}; </select>
- ReaultMap多对一。
第一种 嵌套查询
第二种 根据sql语句的结果集映射<resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <!--复杂的属性单独处理。association:对象,collection:集合--> <association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/> </resultMap> <select id="getAllStudent" resultMap="StudentTeacher"> select * from student; </select> <!--#{id}中id随便写--> <select id="getTeacherById" resultType="Teacher"> select * from teacher where id=#{id}; </select>
<select id="getAllStudent" resultMap="StudentTeacher"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id; </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <!--MyBatis会自动判断Teacher中属性--> <result property="name" column="tname"/> </association> </resultMap>
- ReaultMap一对多。
第一种 嵌套查询
第二种 根据sql语句的结果集映射<resultMap id="teacherStudent" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentsByTid" column="id"/> </resultMap> <select id="getTeacher" resultMap="teacherStudent"> select * from teacher where id=#{id}; </select> <!--#{tid}中tid随便写--> <select id="getStudentsByTid" resultType="Student"> select *from student where tid=#{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"/> </collection> </resultMap> <select id="getTeacher" resultMap="teacherStudent"> select t.id tid,t.name tname,s.id sid,s.name sname from student s,teacher t where s.tid=t.id and t.id=#{id}; </select>
- constructor属性
动态SQL
- if
- choose (when, otherwise)
- trim (where, set去',')
- foreach
- sql。提取公共sql片段。
不难,参数可以使用万能的map。官方文档