MyBatis学习笔记

MyBatis学习笔记

什么是MyBatis?

  • MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

mybatis提供了哪些功能?

  1. 提供了创建Connection,Statement,ResultSet对象的能力,不用开发人员创建这些对象了
  2. 提供了执行sql语句的能力,不用你执行sql
  3. 提供了循环sql,把sql的结果转为java对象,List集合的能力
  4. 提供了关闭资源的能力,不用你关闭Connection,Statement,ResultSet
  • 开发人员做的是:提供sql语句
  • 开发人员提供sql语句–mybatis处理sql–开发人员得到List集合或java对象(表中的数据)

总结:

​ mybatis是一个sql映射框架,提供数据库的操作能力,增强的jdbc

​ 使用mybatis让开发人员集中精神写sql就可以了,不必关心Connection,Statement,ResultSet的创建、销毁,sql的执行

主要类的介绍

  1. Resources:mybatis中的一个类,负责读取主配置文件

    InputStream in = Resources.getResourceAsStream("mybatis.xml");
    
  2. SqlSessionFactoryBuilder:创建SqlSessionFactoryBuilder对象

    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    // 创建SqlSessionFactory对象
    SqlSessionFactory factory = builder.build(in);
    
  3. SqlSessionFactoy:重量级对象,程序创建一个对象耗时比较长,使用资源比较多,在整个项目中,有一个就够用了

    SqlSessionFactory:接口,接口实现类:DefaultSqlSessionFactory

    SqlSessionFactory作用:获取SqlSession对象

    SqlSession sqlSesion = factory.openSession();
    

    openSession()方法说明:

    ​ 1) openSession():无参数的,获取是非自动提交事务的SqlSession对象

    ​ 2) openSession(boolean):openSession(true)获取自动提交事务的SqlSession

    ​ openSession(false)获取非自动提交事务的SqlSession

  4. SqlSession:

    SqlSession接口:定义了关于操作数据的方法

    例如:selectOne(), selectList(), insert(), update(), delete(), commit(), rollback()

    SqlSession接口的实现类DefaultSqlSession

    使用要求:SqlSession对象不是线程安全的,需要在方法内部使用, 在执行sql语句之前,使用open Session()获取SqlSession对象

    ​ 在执行完sql语句后,需要关闭它,执行SqlSession.close(),这样能保证他的使用是线程安全的

mybatis使用步骤

  1. 加入mysql和mybatis的maven依赖,以及资源文件的扫描
	<dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.20</version>
        </dependency>

        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.6</version>
        </dependency>
      </dependencies>

      <build>
        <resources>
          <resource>
            <directory>src/main/java</directory><!--所在的目录-->
            <includes><!--包括目录下的.properties, .xml 文件都会被扫描到-->
              <include>**/*.properties</include>
              <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
          </resource>
        </resources>
 	 </build>
  1. 创建实体类,DepartmentEntity–>保存表中的一行数据
public class DepartmentEntity {
    private int deptno;
    private String dname;
    private String loc;

    public DepartmentEntity(int deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }
    
  	get and set...
  1. 创建持久层的dao接口,定义操作数据库的方法
public interface DepartmentDao {
    public List<DepartmentEntity> selectDepts();

    public int insertDept(DepartmentEntity departmentEntity);

}
  1. 创建dao接口的对应xml配置文件(叫做映射文件:写sql语句的,一般一个表一个sql映射文件)
<?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.qzh.dao.DepartmentDao">
    <!--
        select:表示查询操作

        id:你要执行的sql语句的唯一表示,mybatis会使用这个id的值来找到要执行的sql语句
            可以自定义,但是要求使用接口中的方法名称

        resultType:表示返回结果类型,是sql语句执行后得到ResultSet,遍历这个ResultSet得到java对象的类型,值写返回类型的全限定名称。
    -->
    <select id="selectDepts" resultType="com.qzh.entity.DepartmentEntity">
        select * from dept
    </select>

    <!--插入操作-->
    <insert id="insertDept">
        insert into dept values (#{deptno},#{dname},#{loc})
    </insert>

</mapper>
<!--
    sql映射文件:写sql语句,mybatis会执行这些sql
    1.指定约束文件
        <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        mybatis-3-mapper.dtd是约束文件的名称,扩展名是dtd

    2.约束文件作用:限制,检查在当前文件中出现的标签,属性必须符合mybatis的要求

    3.mapper 是当前文件的根标签,必须的。
      namespace:叫做命名空间,唯一值的,可以是自定义的字符串,要求你使用dao接口的全限定名称。

    4.在当前文件中,可以使用特定的标签,表示数据库的特定操作
        <select>:表示执行查询,里面写的是select语句
        <update>:表示更新数据库的操作,里面写的是update sql语句
        <insert>:表示插入,里面写的是insert语句
        <delete>:表示删除,里面写的是delete语句
-->
  1. 创建mybatis的主配置文件mybatis.xml(放在resources包下,一个项目就一个主配置文件,主配置文件提供了数据库的连接信息和sql映射文件的位置信息)

    1)连接数据库 2)指定mapper文件的位置

<?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>
    <!--settings:控制mybatis全局行为-->
    <settings>
        <!--设置mybatis输出日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--环境配置:数据库的连接信息
        default:必须和某个environment的id的值一样
        告诉mybatis使用哪个数据库的连接信息,也就是访问哪个数据库-->
    <environments default="development">
        <!--environment:一个数据库信息的配置,
            id:一个唯一值,自定义,标识环境的名称-->
        <environment id="development">
            <!--
                transactionManager:mybatis的事务类型
                type:JDBC(表示使用jdbc中的Connection对象的commit,rollback做事务处理)-->
            <transactionManager type="JDBC"/>
            <!--
                dataSource:表示数据源,连接数据库的
            -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/company"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.qzh.dao.DepartmentDao"/>
    </mappers>
</configuration>
  1. 创建使用mybatis类,通过mybatis访问数据库
public class Main {    
	public static void main(String[] args) throws IOException {        		
		//访问mybatis读取dept数据        
		//1.定义mybatis主配置文件的名称,从类路径的根开始(target/classes)        
		String config = "mybatis.xml";        
		//2.读取这个config表示的文件        
		InputStream inputStream = Resources.getResourceAsStream(config);        
		//3.创建了SqlSessionFactoryBuilder对象        
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();        
		//4.创建SqlSessionFactory对象        
		SqlSessionFactory sqlSessionFactory = builder.build(inputStream);        
		//5.获取SqlSession对象,从SqlSessionFactory中获取SqlSession        
		SqlSession sqlSession = sqlSessionFactory.openSession();        
		//6.【重要】指定要执行的sql语句的标识  sql映射文件中的namespace + "." + 标签id的值        
		String sqlId = "com.qzh.dao.DepartmentDao" + "." + "selectDepts";        
		/*DepartmentDao dd = sqlSession.getMapper(DepartmentDao.class);        
		List<DepartmentEntity> deptList = dd.selectDepts();*/        
		// 7.执行sql语句,通过sqlId找到语句        
		List<DepartmentEntity> deptList = sqlSession.selectList(sqlId);        
		// 8.输出结果        
		// deptList.forEach(dept -> System.out.println(dept));        
		for (DepartmentEntity departmentEntity: deptList) {            
			System.out.println(departmentEntity);        
		}        
		// 9.关闭SqlSession对象        
		sqlSession.close();    
	}
}

MyBatisUtil工具类的封装

public class MyBatisUtil {    
	
	private static SqlSessionFactory factory = null;    

	static {        
		String config = "mybatis.xml";        
		try {            
		InputStream in = Resources.getResourceAsStream(config);            
		// 创建SqlSessionFactory对象,使用SqlSessionBuilder            
		factory = new SqlSessionFactoryBuilder().build(in);        
		} catch (IOException e) {            
		e.printStackTrace();        
		}    
	}    
	
	// 获取SqlSession的方法    
	public static SqlSession getSqlSession() {        
		SqlSession sqlSession = null;        
		if (factory != null) {            
		// mybatis默认不是自动提交事务的,所以在insert,update,delete后要手工提交事务            
		sqlSession = factory.openSession(); // 非自动提交事务        
		}        
	return sqlSession;    
	}
}

使用动态代理机制执行sql

  • 动态代理:mybatis帮你创建dao接口实现类,在实现类中调用SqlSession的方法执行sql语句【使用SqlSession.getMapper(dao接口.class)获取这个dao接口的实现类对象】

    1.获取SqlSession对象,SqlSessionFactory.openSession();

    2.使用getMapper方法获取某个接口的对象,sqlSession.getMapper(dao接口.class)

    3.使用dao接口中的方法,调用方法就执行了mapper文件中的sql语句

 	@Test    
 	public void testSelectDepts() {        
	 	/*        
	 	* 使用mybatis的动态代理机制,使用SqlSession.getMapper(dao接口)        
		* getMapper能获取dao接口对应的实现类对象        * 
		* */        	
		SqlSession sqlSession = MyBatisUtils.getSqlSession();        
		DepartmentDao dao = sqlSession.getMapper(DepartmentDao.class);        
		// 调用dao的方法,执行数据库的操作        
		List<DepartmentEntity> depts = dao.selectDepts();        
		depts.forEach(dept -> System.out.println(dept));    
	}

使用动态代理方式的要求:

  1. dao接口和mapper文件放在一起,同一个目录
  2. dao接口和mapper文件名称一致
  3. mapper文件中的namespace的值是dao接口的全限定名称
  4. mapper文件的,,,等的id是接口中的方法名称
  5. dao接口中不要使用重载方法,不用使用同名的、不同参数的方法

parameterType的使用

parameterType:写在mapper文件中的一个属性,表示dao接口中方法的参数的数据类型

一个参数的传入

例如:

接口中的方法:

	/*    
	* 一个简单类型的参数:    
	*   简单类型:mybatis把java的基本数据类型和String都叫简单类型    
	*   在mapper文件获取简单类型的一个参数的值,使用#{任意字符}    
	**/
	public DepartmentEntity selectDeptByNo(Integer no);

对应的xml文件:

	<!--        parameterType:dao接口中方法参数的数据类型        
	parameterType它的值是java的数据类型全限定名称或者是mybatis定义的别名        
	例如:parameterType="java.lang.Integer”或者是parameterType="int”				
	注意:parameterType不是强制的,mybatis通过反射机制也能够发现接口参数的类型,所以可以没有,一般我们也不写				
	使用#{}之后,mybatis执行sql是使用的jdbc中的PreparedSatement对象		
	由mybatis执行下面的代码:		
	1.mybatis创建Connection,PreparedStatement对象		  
	String sql = "select deptno, dname, loc from dept where deptno = ?";		  
	PreparedStatement pst = conn.preparedStatement(sql);		  
	pst.setInt(...);		
	2.执行sql封装为resultType="com.qzh.entity.DepartmentEntity"这个对象		  
	ResultType rs = ps.executeQuery();    	  
	while(rs.next) {			  
	// 从数据库获取表的一行数据,存到一个java对象的属性中			  
	...		  
	}		  
	return department; // dao方法调用的返回值	-->    
	<select id="selectDeptByNo" parameterType="java.lang.Integer" 	resultType="com.qzh.entity.DepartmentEntity">        
	select deptno, dname, loc from dept where deptno = #{no}    </select>

多个参数—使用@Param命名参数

例如:

接口中的方法:

	/*    
	* 多个参数:命名参数,在形参定义的前面加入@Param("自定义参数名称")    
	* */
	public DepartmentEntity selectMultipleParam(@Param("myno") Integer no, @Param("myname") String name);

对应的xml文件:

 	<!--多个参数,使用@Param命名-->	
 	<select id="selectDeptByNo" parameterType="java.lang.Integer" 	resultType="com.qzh.entity.DepartmentEntity">        
 	select * from dept where deptno = #{myno} or dname = #{myname}    </select>

多个参数—使用对象

例如:

接口中的方法:

	/*    
	* 多个参数,使用java对象作为接口中方法的参数    * 
	* */    
	public DepartmentEntity selectByObject(DepartmentEntity departmentEntity);

对应的xml文件:

	<!--多个参数,使用java对象的属性值,作为参数的实际值        
	使用对象语法:#{属性名, javaType=类型名称, jdbcType=数据类型} (完整的语法格式,很少用)        
	javaType:在java中的属性数据类型        
	jdbcType:在数据库中属性数据类型        
	例如:#{deptno,javaType=java.lang.Integer,jdbcType=INTEGER}        
	使用简化版:            
	#{属性名} (javaType,jdbcType的值mybatis反射能获取,不用提供)    
	-->    
	<select id="selectByObject" resultType="com.qzh.entity.DepartmentEntity">        
		select * from dept where deptno = #{deptno} and dname  = #{dname}    
	</select>

PS:#和$区别

  1. #使用 ? 在sql语句中用作占位符,使用PreparedStatement执行sql,效率高
  2. #能够避免sql注入的问题,更安全
  3. $不使用占位符,是字符串连接方式,使用Statement对象执行sql,效率低
  4. $有sql注入的风险,缺乏安全性
  5. $:可以替换表名或者列名

mybatis的输出结果

1.简单类型

​ resultType采用别名或者全限定名称

  1. 对象类型,指sql语句执行完毕后,数据转为java对象

​ 处理方式:

​ a.mybatis执行sql语句,然后mybatis调用类的无参数构造方法,创建对象

​ b.mybatis把ResultSet指定列值赋给同名的属性

	<select id="selectMultipleParam" resultType="com.qzh.entity.DepartmentEntity">        
	
		select * from dept where deptno = #{myno} or dname  = #{myname}    
	</select>

​ 对等的jdbc

	ResultSet rs = ps.executeQuery();	while(rs.next) {        ...    }
  1. 定义自定义类型的别名

    1)在mybatis主配置文件中定义,使用定义别名

    2)可也在resultType中使用自定义的别名

    	<!--定义别名-->    
    	<typeAliases>       
    	 <!--      
    	 可以指定一个类型的一个自定义别名            
    	 type:自定义类型的全限定名称            
    	 alias:别名(短小,容易记忆的)        
    	 -->        
    	 <typeAlias type="com.qzh.entity.DepartmentEntity" alias="de"/>       
    	  <!--            
    	  第二种方式:            
    	  <package> name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)       
    	   -->       
    	 <package name="com.qzh.entity"/>    </typeAliases>
    
  2. 返回Map

    接口中的方法:

    	// 定义方法返回Map   
    	Map<Object, Object> selectMqpById(Integer no);
    

    对应的映射文件

    	<!--返回Map        
    	1)列名是map的key,列值是map的value       
     	2)返回map的时候最多只能返回一条记录  
     	-->    
     	<select id="selectMqpById" resultType="map">        
     		select deptno, dname from dept where deptno = #{no}    
     	</select>
    
  3. 数据库中表的列名和实体对象的属性名不一样

    a.第一种方式:

    ​ resultMap:结果映射,指定列名和java对象的属性对应关系

    ​ 使用情况:

    ​ 1.自定义列值赋值给哪个属性

    ​ 2.当你的列名和属性名不一样时,一定使用resultMap

    ​ 映射文件:

    	<!--使用resultMap        
    	1)先定义resultMap        
    	2)在select标签,使用resultMap来引用定义的    -->    
    	<!--定义resultMap        
    	id:自定义名称,表示你定义的这个resultMap        
    	type:java类型的全限定名称    
    	-->    
    	<resultMap id="deMap" type="com.qzh.entity.DepartmentEntity">        
        	<!--列名和java属性的关系-->        
        	<!--主键列,使用id标签  column:列名   property:java类型的属性名-->        
        	<id column="deptno" property="deptno"/>        
        	<!--非主键列,使用result-->        
        	<result column="dname" property="dname"/>    
    	</resultMap>    
    	<select id="selectDepts" resultMap="deMap">        
    		select deptno, dname from dept    
    	</select>
    

    PS:resultMap和resultType不要一起用,二选一

    b.第二种方式:

    ​ resultType的默认原则是同名的列值赋值给同名的属性,使用列别名(java对象的属性名)

Like查询的两种方式

  1. 接口中的方法:

    	// 第一种模糊查询,在java代码中指定like的内容    
    	List<DepartmentEntity> selectLikeOne(String name);
    

    映射文件:

    	<!--第一种like,在Java代码中指定like的内容|-->    
    	<select id="selectLikeOne" resultType="com.qzh.entity.DepartmentEntity">        
    		select * from dept where dname like #{name}    
    	</select>
    
  2. 接口中的方法:

    	// 第二种模糊查询,dname就是a,在mapper中拼接 like "%" a "%"    
    	List<DepartmentEntity> selectLikeTwo(String name);
    

    映射文件:

    	<!--第二种方式:在mapper文件中拼接 like 的内容-->    
    	<select id="selectLikeTwo" resultType="com.qzh.entity.DepartmentEntity">        
    		select * from dept where dname like "%" #{name} "%"    
    	</select>
    

动态SQl

  • 动态sql:sql的内容是变化的,可以根据条件获取到不同的sql语句,主要是where部分发生变化

  • 动态sql的实现,使用的是mybatis提供的标签,, ,

    • 是判断条件的,条件为true则会把if之间的sql加入到主sql之后

      语法:

      <if test="判断java对象的属性值">	
      	部分sql语句
      </if>
      

      例如:

      接口中的方法:

      	// 动态sql,使用java对象作为参数    
      	List<DepartmentEntity> selectDeptIf(DepartmentEntity departmentEntity);
      

      映射文件:

      	<!--if        
      	<if test="使用参数java对象的属性值作为判断条件, 语法 属性 = xxx值">    
      	-->    
      	<select id="selectDeptIf" resultType="com.qzh.entity.DepartmentEntity">        
      		select deptno, dname, loc from dept        
      		where 1=1        
      		<if test="dname != null and dname != ''">            
      			and dname = #{dname}        
      		</if>        
      		<if test="deptno >10">            
      			and deptno > #{deptno}        
      		</if>    
      	</select>
      

      测试:

      	DepartmentEntity de = new DepartmentEntity(20, "abc", "abc");        
      	List<DepartmentEntity> depts = dao.selectDeptIf(de);        
      	depts.forEach(dept -> System.out.println(dept));
      

      测试结果:

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sbosU97q-1626786707059)(C:\Users\www13\AppData\Roaming\Typora\typora-user-images\image-20210719163315763.png)]

    • 用来包含多个的,当多个if有一个成立的,会自动增加一个where关键字,并去掉多余的and,or等

      例如:

      接口中的方法:

      	// where的使用    
      	List<DepartmentEntity> selectDeptWhere(DepartmentEntity departmentEntity);
      

      映射文件:

      	<!--where:        
      	<where> <if> <if> ... </where>    
      	-->    
      	<select id="selectDeptWhere" resultType="com.qzh.entity.DepartmentEntity">        
      		select deptno, dname, loc from dept        
      		<where>            
      		<if test="dname != null and dname != ''">                
      			dname = #{dname}            
      		</if>            
      		<if test="deptno >10">                
      			and deptno > #{deptno}            
      		</if>        
      		</where>    
      	</select>
      

      测试结果:

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mugxmQWg-1626786707061)(C:\Users\www13\AppData\Roaming\Typora\typora-user-images\image-20210719164033679.png)]

    • 循环java中的数组,list集合的。主要用在sql的in语句中

      例如:

      接口中的方法:

      	// foreach 用法1    
      	List<DepartmentEntity> selectForeachOne(List<Integer> noList);    
      	// foreach 用法2    
      	List<DepartmentEntity> selectForeachTwo(List<DepartmentEntity> deptList);
      

      映射文件:

      	<!--foreach使用1,List<Integer>        
      	collection:表示接口中的方法参数类型,如果是数组使用array,如果是list集合使用list        
      	item:自定义的,表示数组或集合成员的变量        
      	open:循环开始时的字符        
      	close:循环结束时的字符        
      	separator:集合成员之间的分隔符    
      	-->    
      	<select id="selectForeachOne" resultType="com.qzh.entity.DepartmentEntity">        
      		select * from dept where deptno in        
      		<foreach collection="list" item="deptno" open="(" close=")" separator=",">            
      			#{deptno}        
      		</foreach>    
      	</select> 
      	   
      	<!--foreach使用2,List<DepartmentEntity>|-->    
      	<select id="selectForeachTwo" resultType="com.qzh.entity.DepartmentEntity">        
      		select * from dept where deptno in (        
      		<foreach collection="list" item="dept" separator=",">            
      			#{dept.deptno}        
      		</foreach>        
      		)    
      	</select>
      

sql代码片段

复用部分sql语句

步骤:

  • 先定义 < sql id=“自定义名称唯一”> sql语句,表名,字段等 < /sql>
  • 再使用 < include refid=“id的值” />

例如:

	<!--定义sql片段-->    
	<sql id="deptSql">        
		select * from dept    
	</sql>	
	<select id="selectForeachTwo" resultType="com.qzh.entity.DepartmentEntity">        
		<include refid="deptSql" /> where deptno in (        
		<foreach collection="list" item="dept" separator=",">            
			#{dept.deptno}        
		</foreach>        
		)    
	</select>

数据库的属性配置文件

把数据库连接信息放到一个单独的文件中,和mybatis主配置文件分开,目的是便于修改,保存,处理多个数据库的信息

  • 在resources目录中定义一个属性配置文件,xxx.properties,例如 jdbc.properties

    在属性配置文件中,定义数据,格式是 key=value

    key:一般使用 . 做多级目录的

    例如 jdbc.mysql.driver , jdbc.driver, mydrier

    jdbc.driver=com.mysql.cj.jdbc.Driver

    jdbc.url=jdbc:mysql://localhost:3306/…

    jdbc.username=root

    jdbc.password=root

  • 在mybatis的主配置文件,使用指定文件的位置

    在需要使用值的地方,使用${key}

  • mapper文件,使用指定路径

例如mybatis.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>    
	
	<!--指定properties文件的位置,从类路径根开始找文件-->    
	<properties resource="jdbc.properties" />    
	
	<!--settings:控制mybatis全局行为-->    
	<settings>        
		<!--设置mybatis输出日志-->        
		<setting name="logImpl" value="STDOUT_LOGGING"/>    
	</settings>    
	
	<!--定义别名-->    
	<typeAliases>       
		 <!--            
		 第一种方式:            
		 可以指定一个类型的一个自定义别名            
		 type:自定义类型的全限定名称            
		 alias:别名(短小,容易记忆的)        
		 -->        
		 <typeAlias type="com.qzh.entity.DepartmentEntity" alias="de"/>        
		 <!--            
		 第二种方式:            
		 <package> name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)        
		 -->        
		 <package name="com.qzh.entity"/>    
	</typeAliases>    
	<!--配置插件-->    
	<plugins>        
		<plugin interceptor="com.github.pagehelper.PageInterceptor" />    
	</plugins>    
	<!--环境配置:数据库的连接信息        
		default:必须和某个environment的id的值一样        
		告诉mybatis使用哪个数据库的连接信息,也就是访问哪个数据库
	-->    
	<environments default="development">        
		<!--environment:一个数据库信息的配置,            
			id:一个唯一值,自定义,标识环境的名称-->        
		<environment id="development">            
			<!--                
			transactionManager:mybatis的事务类型                
			type:JDBC(表示使用jdbc中的Connection对象的commit,rollback做事务处理)
			-->            
			<transactionManager type="JDBC"/>            
			<!--                
			dataSource:表示数据源,连接数据库的                            在java体系中,规定实现了javax.sql.DataSource接口的都是数据源                            数据源表示Connection对象的                
			type:指定数据源的类型                    
				1)POOLED:使用连接池,mybatis会创建PooledDataSource类                    
				2)UNPOOLED:不使用连接池,在每次执行sql语句,先创建连接,执行sql,再关闭连接                                
				   mybatis会闯进啊一个UnPooledDataSource,管理Connection对象的使用                    
				3)JNDI:java命名和目录服务(windows注册表)            
				-->            
			<dataSource type="POOLED">                
			<!--<property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->                
			<property name="driver" value="${jdbc.driver}"/>                
			<!--<property name="url" value="jdbc:mysql://localhost:3306/company"/>-->                
			<property name="url" value="${jdbc.url}"/>                
			<!--<property name="username" value="root"/>-->                
			<property name="username" value="${jdbc.username}"/>                
			<!--<property name="password" value="root"/>-->                
			<property name="password" value="${jdbc.password}"/>            
			</dataSource>        
		</environment>    
	</environments>    
	<!--sql mapper(sql映射文件)的位置-->    
	<mappers>        
		<!--第一种方式:指定多个mapper文件-->        
		<!--<mapper class="com.qzh.dao.DepartmentDao"/>-->        
		<!--第二种方式,使用包名            
			name:xml文件(mapper文件)所在的包名,这个包中所有xml文件一次都能加载给mybatis            
			使用<package>要求:                
				1.mapper文件名称需要和接口名称一样,区分大小写                
				2.mapper文件和dao接口需要在同一目录中        
		-->        
		<package name="com.qzh.dao"/>    
	</mappers>
</configuration>

PageHelper

PageHelper做数据分页的

  1. 添加maven依赖

    	<dependency>      
    		<groupId>com.github.pagehelper</groupId>      			
    		<artifactId>pagehelper</artifactId>      
    		<version>5.1.2</version>    
    	</dependency>
    
  2. 在mybatis全局控制文件中配置插件

    	<!--配置插件-->   
    	 <plugins>       
    	 	<plugin interceptor="com.github.pagehelper.PageInterceptor" />
    	 </plugins>
    

例如:

	@Test    
	public void testSelectAll() {        
		SqlSession sqlSession = MyBatisUtils.getSqlSession();        
		DepartmentDao dao = sqlSession.getMapper(DepartmentDao.class);        
		// 加入PageHelper的方法,分页        
		// pageNum: 第几页,从1开始        
		// pageSize: 一页中有多少行数据        
		// 公式:((pageNum-1)*pageSize,pageSize)        
		PageHelper.startPage(1,3); // 表示一页有三行数据        
		List<DepartmentEntity> deptList = dao.selectDepts();        
		deptList.forEach(dept -> System.out.println(dept));        
		sqlSession.close();    
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值