Mybatis3

文章目录

    • 1.介绍
      • 1.1为什么要用mybatis?
      • 1.2 下载
    • 2.helloWorld
    • 3.接口式编程
    • 4.相关重要类或配置
      • 4.1 配置文件
      • 4.2 session
      • 4.3 dtd配置
      • 4.4 引入properties外部文件
      • 4.5 打印日志配置
    • 5.全局配置文件mybatis-config.xml
      • 5.1 properties 文件引入
      • 5.2 settings 属性设置
      • 5.3 typeAliases 给类起别名
      • 5.4 typeHandlers 类型处理器
      • 5.5 plugins 插件
      • 5.6 enviroments 运行环境
      • 5.7 databaseIdProvider 多数据库支持 (相当于给数据库起别名)
      • 5.8 mappers sql映射注册
    • 6.增删改查
    • 7.sql映射文件
      • 7.1 insert
      • 7.2 多个命名参数
      • 7.3 参数的获取
      • 7.4 select
      • 7.5
    • 8.动态SQL
      • 8.1 if
      • 8.2 choose(when,otherwise)
      • 8.3 trim(where,set)
      • 8.4 foreach
      • 8.5 bind
      • 8.6 includ 提取重复sql
    • 9.

1.介绍

iBatis3.x正式更名为MyBatis
• MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
• MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
• MyBatis 可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java
Objects,普通的Java对象)映射成数据库中的记录.
官方文档

1.1为什么要用mybatis?

Mybatis3_第1张图片
Mybatis3_第2张图片
总结:

• MyBatis是一个半自动化的持久化层框架。
JDBC
– SQL夹在Java代码块里,耦合度高导致硬编码内伤
– 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见
Hibernate和JPA
– 长难复杂SQL,对于Hibernate而言处理也不容易
– 内部自动生产的SQL,不容易做特殊优化。
– 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难。
导致数据库性能下降。
• 对开发人员而言,核心sql还是需要自己优化
• sql和java编码分开,功能边界清晰,一个专注业务、
一个专注数据。

1.2 下载

jar包下载
Mybatis3_第3张图片

2.helloWorld

整体结构:
Mybatis3_第4张图片
IDEA是不会编译src的java目录的xml文件,所以在Mybatis的配置文件中找不到xml文件!(也有可能是Maven构建项目的问题)
因此我们把xml文件都放置在resource下,这样就不会错了。

1.创建一个Maven工程
Mybatis3_第5张图片
2.pom.xml配置

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
  </dependencies>

3.其他配置文件
mybatis-config.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.10.128:3306/mavendb"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="conf/EmpMapper.xml"/>
    </mappers>
</configuration>

EmpMapper.xml

<?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.zy.entity.EmpMapper">
<!-- 
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
如果表中的字段名和实体类属性名不相同,那么查询出来的结果为 null。
 -->
	<select id="getEmpById" resultType="com.zy.entity.Emp">
		select emp_id eId,emp_name eName,email eEmail,gender eGender,d_id dId from tbl_emp where emp_id = #{id}
	</select>
</mapper>

4.实体类

public class Emp {
    private Integer eId;
    private String eName;
    private String eGender;
    private String eEmail;
    private String dId;

5.测试代码

    @Test
    public void testCon() throws IOException {

        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        Emp emp = sqlSession.selectOne("com.zy.entity.EmpMapper.getEmpById", 1);
        System.out.println("emp = " + emp.toString());
    }

Mybatis3_第6张图片

3.接口式编程

在这里插入图片描述
如上图所示,当参数我们传递字符串比如“1”也可以,不过执行中会报错或者记录找不到,这是因为我们并没有对传递的参数或者接受的结果进行类型检查,所以后续应该采用接口式来传递

Mybatis3_第7张图片

1.定义接口EmpMapperService

public interface EmpMapperService {
    public Emp getEmpById(Integer id);
}

2.定义配置文件EmpMapperService.xml

<?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.zy.service.EmpMapperService">
    <select id="getEmpById" resultType="com.zy.entity.Emp">
        select emp_id eId,emp_name eName,email eEmail,gender eGender,d_id dId from tbl_emp where emp_id = #{id}
    </select>
</mapper>

注意:namespace一定指定为接口类全路径,id名一定是接口里的方法名

3.执行

    @Test
    public void testInterface() throws IOException {

        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过getMapper获取EmpMapperService接口的一个实现类(代理类)
        EmpMapperService mapper = sqlSession.getMapper(EmpMapperService.class);
        Emp empById = mapper.getEmpById(1);
        System.out.println("empById.toString() = " + empById.toString());

    }

在这里插入图片描述

4.相关重要类或配置

4.1 配置文件

mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等…系统运行环境信息
sql映射文件:保存了每一个sql语句的映射信息:将sql抽取出来。

4.2 session

1.SqlSession代表和数据库的一次会话;用完必须关闭;
2.SqlSession和connection一样她都是非线程安全。每次使用都应该去获取新的对象。(不能共享session,因为A用了session后关闭,那么B线程再用就会报错)
3.mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。(将接口和xml进行绑定)
EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

4.3 dtd配置

参考

4.4 引入properties外部文件

像上面获取数据库连接,我们可以把它放到配置文件里,方便以后修改

1.新增配置文件dbconfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.10.128:3306/mavendb
jdbc.username=root
jdbc.password=root

2.mybatis-config.xml新增properties

<configuration>
	<!--新增外部文件引入-->
    <properties resource="conf/dbconfig.properties"></properties>

    <environments default="development">
        <environment id="development">
            <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>
        <mapper resource="conf/EmpMapper.xml"/>
        <mapper resource="conf/EmpMapperService.xml"/>
    </mappers>
</configuration>

Mybatis3_第8张图片

4.5 打印日志配置

说明
1.pom.xml

    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>1.7.12version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>1.7.12version>
    dependency>

2.增加log4j.properties

# Attach appender A1 to root. Set root level to Level.DEBUG.
log4j.rootLogger=DEBUG, Console
#设置打印到显示器上
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Threshold=DEBUG
log4j.appender.Console.encoding=UTF-8
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{yyyyMMdd hh:mm:ss}] %F.%L: %m%n

3.全局配置指定日志实现类mybatis-config.xml
其实这个配置不配置日志都会打印

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    settings>

Mybatis3_第9张图片

5.全局配置文件mybatis-config.xml

5.1 properties 文件引入

引入外部配置文件,使用参考上面4.4

5.2 settings 属性设置

	
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
	settings>

5.3 typeAliases 给类起别名

	
	<typeAliases>
		
		
		
		
		<package name="com.mybatis.bean"/>
		
		
	typeAliases>

5.4 typeHandlers 类型处理器

Mybatis3_第10张图片
Mybatis3_第11张图片

5.5 plugins 插件

5.6 enviroments 运行环境

	
		 
	<environments default="dev_mysql">
		<environment id="dev_mysql">
			<transactionManager type="JDBC">transactionManager>
			<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>

5.7 databaseIdProvider 多数据库支持 (相当于给数据库起别名)

Mybatis3_第12张图片

	
	<databaseIdProvider type="DB_VENDOR">
		
		<property name="MySQL" value="mysql"/>
		<property name="Oracle" value="oracle"/>
		<property name="SQL Server" value="sqlserver"/>
	databaseIdProvider>
	

Mybatis3_第13张图片

5.8 mappers sql映射注册

	
	<mappers>
		
		
		
		
		
		<package name="com.atguigu.mybatis.dao"/>
	mappers>

6.增删改查

EmpMapperService

	/**
	 * 增删改
	 * 1、mybatis允许增删改直接定义以下类型返回值
	 * 		Integer、Long、Boolean、void
	 * 2、我们需要手动提交数据
	 * 		sqlSessionFactory.openSession();===》手动提交
	 * 		sqlSessionFactory.openSession(true);===》自动提交
	 */
public interface EmpMapperService {
    public Emp getEmpById(Integer id);
    public Long addEmp(Emp emp);
    public boolean updateEmp(Emp emp);
    public void deleteEmpById(Integer id);
}

EmpMapperService.xml

	//#{parm}:表示从对象中获取属性或者获取传参 
    <select id="getEmpById" resultType="com.zy.entity.Emp">
        select emp_id eId,emp_name eName,email eEmail,gender eGender,d_id dId from tbl_emp where emp_id = #{id}
    </select>
    <insert id="addEmp" parameterType="com.zy.entity.Emp">
        INSERT INTO tbl_emp(emp_name, gender, email, d_id)
        VALUES (#{eName}, #{eGender}, #{eEmail}, #{dId});
    </insert>
    <update id="updateEmp">
        update tbl_emp
        set emp_name=#{eName},email=#{eEmail},gender=#{eGender},d_id=#{dId}
        where emp_id=#{eId}
    </update>
    <delete id="deleteEmpById">
        delete from tbl_employee where emp_id=#{id}
    </delete>

测试

    @Test
    public void testAUD(){

        String resource = "conf/mybatis-config.xml";
        SqlSession sqlSession = null;
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
            EmpMapperService mapper = sqlSession.getMapper(EmpMapperService.class);
            
            //新增
            Emp emp = new Emp();
            emp.seteName("员工A");
            emp.seteEmail("[email protected]");
            emp.seteGender("M");
            emp.setdId(2);
            mapper.addEmp(emp);
            //修改
            Emp emp2 = new Emp();
            emp.seteId(2);
            emp.seteName("员工B");
            emp.seteEmail("[email protected]");
            emp.seteGender("W");
            emp.setdId(2);
            mapper.updateEmp(emp2);
            //删除
            mapper.deleteEmpById(2);

            sqlSession.commit();

        }catch (Exception e){
            System.out.println("e = " + e.getMessage());
        }finally {
            sqlSession.close();
        }
    }

Mybatis3_第14张图片

7.sql映射文件

7.1 insert

1.获取主键(增加下面两个属性)

	
    <insert id="addEmp" parameterType="com.zy.entity.Emp" useGeneratedKeys="true" keyProperty="eId">
        INSERT INTO tbl_emp(emp_name, gender, email, d_id)
        VALUES (#{eName}, #{eGender}, #{eEmail}, #{dId});
    insert>
	
	<insert id="addEmp" databaseId="oracle">
		
		<selectKey keyProperty="id" order="BEFORE" resultType="Integer">
			
			
			select EMPLOYEES_SEQ.nextval from dual 
			
		selectKey>
		
		
		
		insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) 
		values(#{id},#{lastName},#{email}) 
		
	insert>

7.2 多个命名参数

单个参数:mybatis不会做特殊处理,
	#{参数名/任意名}:取出参数值。
	
多个参数:mybatis会做特殊处理。
	多个参数会被封装成 一个map,
		key:param1...paramN,或者参数的索引也可以
		value:传入的参数值
	#{}就是从map中获取指定的key的值;
方式一:
定义:
public Employee getEmpByIdAndLastName(Integer id,String lastName);
使用:
 	<select id="getEmpByIdAndLastName" resultType="com.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{param1} and last_name=#{param1}
 	select>

方式二:
定义:
public Employee getEmpByIdAndLastName(@Param("id")Integer id,@Param("lastName")String lastName);
使用:
 	<select id="getEmpByIdAndLastName" resultType="com.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 	select>

POJO:
如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo;
	#{属性名}:取出传入的pojo的属性值	

Map:
如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map
	#{key}:取出map中对应的值

	public Employee getEmpByMap(Map<String, Object> map);
	
 	<select id="getEmpByMap" resultType="com.mybatis.bean.Employee">
 		select * from ${tableName} where id=${id} and last_name=#{lastName}
 	select>
 	
	Map<String, Object> map = new HashMap<>();
	map.put("id", 2);
	map.put("lastName", "Tom");
	map.put("tableName", "tbl_employee");
	Employee employee = mapper.getEmpByMap(map);
TO:
如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象
Page{
	int index;
	int size;
}


public Employee getEmp(@Param("id")Integer id,String lastName);
	取值:id==>#{id/param1}   lastName==>#{param2}

public Employee getEmp(Integer id,@Param("e")Employee emp);
	取值:id==>#{param1}    lastName===>#{param2.lastName/e.lastName}

##特别注意:如果是Collection(List、Set)类型或者是数组,
		 也会特殊处理。也是把传入的list或者数组封装在map中。
			key:Collection(collection),如果是List还可以使用这个key(list)
				数组(array)
public Employee getEmpById(List<Integer> ids);
	取值:取出第一个id的值:   #{list[0]}

7.3 参数的获取

注意:下面是日志打印出来的执行sql语句
select * from tbl_employee where id=${id} and last_name=#{lastName}
Preparing: select * from tbl_employee where id=2 and last_name=?

#{}:可以获取map中的值或者pojo对象属性的值;
${}:可以获取map中的值或者pojo对象属性的值;
	区别:
		#{}:是以预编译的形式,将参数设置到sql语句中;PreparedStatement;防止sql注入
		${}:取出的值直接拼装在sql语句中;会有安全问题;
		大多情况下,我们去参数的值都应该去使用#{};
		
		原生jdbc不支持占位符的地方我们就可以使用${}进行取值
		比如分表、排序。。。;按照年份分表拆分
			select * from ${year}_salary where xxx;
			select * from tbl_employee order by ${f_name} ${order}

#{}:更丰富的用法:
	规定参数的一些规则:
	javaType、 jdbcType、 mode(存储过程)、 numericScale、
	resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能);

	jdbcType通常需要在某种特定的条件下被设置:
		在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle(报错);
		
		JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生Jdbc的OTHER类型,oracle不能正确处理;
		
		由于全局配置中:jdbcTypeForNull=OTHER;oracle不支持;两种办法
		1、#{email,jdbcType=OTHER};
		2、jdbcTypeForNull=NULL
			<setting name="jdbcTypeForNull" value="NULL"/>

7.4 select

	//返回list
	public List<Employee> getEmpsByLastNameLike(String lastName);
	
	<select id="getEmpsByLastNameLike" resultType="com.mybatis.bean.Employee">
		select * from tbl_employee where last_name like #{lastName}
	</select>
	
	List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
	for (Employee employee : like) {
		System.out.println(employee);
	}
	//返回map
	//多条记录封装一个map:Map:键是这条记录的主键,值是记录封装后的javaBean
	//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
	@MapKey("lastName")
	public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);

 	<select id="getEmpByLastNameLikeReturnMap" resultType="com.mybatis.bean.Employee">
 		select * from tbl_employee where last_name like #{lastName}
 	</select>

	Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
	System.out.println(map);

7.5

8.动态SQL

8.1 if

	 
	 
	 <select id="getEmpsByConditionIf" resultType="com.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	where
	 	
	 	<if test="id!=null">
	 		id=#{id}
	 	if>
	 	<if test="lastName!=null && lastName!=""">
	 		and last_name like #{lastName}
	 	if>
	 	<if test="email!=null and email.trim()!=""">
	 		and email=#{email}
	 	if> 
	 	
	 	<if test="gender==0 or gender==1">
	 	 	and gender=#{gender}
	 	if>
	 select>

8.2 choose(when,otherwise)

	 
	 <select id="getEmpsByConditionChoose" resultType="com.mybatis.bean.Employee">
	 	select * from tbl_employee 
	 	<where>
	 		
	 		<choose>
	 			<when test="id!=null">
	 				id=#{id}
	 			when>
	 			<when test="lastName!=null">
	 				last_name like #{lastName}
	 			when>
	 			<when test="email!=null">
	 				email = #{email}
	 			when>
	 			<otherwise>
	 				gender = 0
	 			otherwise>
	 		choose>
	 	where>
	 select>

8.3 trim(where,set)

where

			//查询的时候如果某些条件没带可能sql拼装会有问题
			//1、给where后面加上1=1,以后的条件都and xxx.
			//2、mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
			//where只会去掉第一个多出来的and或者or!!!!

	 <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	
	 	<where>
		 	<if test="id!=null">
		 		id=#{id}
		 	if>
		 	<if test="lastName!=null && lastName!=""">
		 		and last_name like #{lastName} //注意:只会去掉第一个多余的and
		 	if>
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}  //注意:只会去掉第一个多余的and
		 	if>
	 	where>
	 select>

trim:自定义字符串截取

	 
	 <select id="getEmpsByConditionTrim" resultType="com.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	
	 	
	 	<trim prefix="where" suffixOverrides="and">
	 		<if test="id!=null">
		 		id=#{id} and
		 	if>
		 	<if test="lastName!=null && lastName!=""">
		 		last_name like #{lastName} and
		 	if>
		 	<if test="email!=null and email.trim()!=""">
		 		email=#{email} and
		 	if> 
		 	
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	if>
		 trim>
	 select>

set

	 
	 <update id="updateEmp">
	 	
	 	update tbl_employee 
		<set>
			<if test="lastName!=null">
				last_name=#{lastName},
			if>
			<if test="email!=null">
				email=#{email},
			if>
			<if test="gender!=null">
				gender=#{gender}
			if>
		set>
		where id=#{id} 

	 update>

8.4 foreach

	 
	 <select id="getEmpsByConditionForeach" resultType="com.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	
	 	<foreach collection="ids" item="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	foreach>
	 select>

8.5 bind

	  
	  <select id="getEmpsTestInnerParameter" resultType="com.mybatis.bean.Employee">
	  		
	  		<bind name="_lastName" value="'%'+lastName+'%'"/>
	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null">
	  				where last_name like #{_lastName}
	  			if>
	  		if>
	  select>

8.6 includ 提取重复sql

	  
	  <sql id="insertColumn">
	  		<if test="_databaseId=='oracle'">
	  			employee_id,last_name,email
	  		if>
	  		<if test="_databaseId=='mysql'">
	  			last_name,email,gender,d_id
	  		if>
	  sql>

	<insert id="addEmps">
	 	insert into tbl_employee(
	 		<include refid="insertColumn">include>
	 	) 
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		foreach>
	 insert>

9.

d_d

你可能感兴趣的:(#,Mybatis)