Mybatis个人笔记

复习框架编写笔记,主要是方便自己查找


Mybatis官网: 传送门

1、环境搭建

  • 引入依赖
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>x.x.x</version>
</dependency>

<!--mysql数据库-->
<dependency>
	<groupId>mysql</groupId>   
	<artifactId>mysql-connector-java</artifactId>
	<version>x.x.x</version>
</dependency>
  • 创建实体类
  • 持久层接口
  • 编写映射文件
<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</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>
  <environments default="mysql">
    <environment id="mysql">
      <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>
  <!--引入jdbc配置文件-->
  <properties resource="jdbc.properties"></properties>
  
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    <!--<package name="com.xyulu.dao"/>-->
  </mappers>
</configuration>
  • 使用
String resource = "org/mybatis/example/mybatis-config.xml";  //从resources目录寻找
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();

2、配置文件详解 configuration

只简单列了几个,配置文件部分详细见官网吧 配置文件详解

2.1、属性 properties

这些属性可以在外部进行配置,并可以进行动态替换
<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>
外部配置,前提得编写jdbc.properties配置文件
<properties resource="jdbc.properties"></properties>

2.2、设置 settings

太多了、、、见官网吧,上附传送门
<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <!--略略略略略略略-->
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

2.3、类型别名 typeAliases

当这样配置时,不需要写全类名。也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

2.4、类型处理器 typeHandlers

MyBatis 在设置预处理语句(PreparedStatement)中的参数或从结果集中取出一个值时, 都会用类型处理器将获取到的值以合适的方式转换成 Java 类型

2.5、插件 plugins

<!-- mybatis-config.xml -->
<plugins>
  <!--这是官网的例子,官网编写的插件-->
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>

2.6、环境配置 environments

详见官网,太多了

尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。如果你想连接两个数据库,就需要创建两个 SqlSessionFactory 实例

2.7、映射器 mappers

<!--四选一-->
<mappers>
  <!-- 最常用的 -->
  <package name="org.mybatis.builder"/>
  <!-- 使用映射器接口实现类的完全限定类名 -->
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <!-- 使用相对于类路径的资源引用 -->
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <!-- 使用完全限定资源定位符(URL) -->
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>

3、XML映射文件

  • insert – 映射插入语句。
  • update – 映射更新语句。
  • delete – 映射删除语句。
  • select – 映射查询语句。
  • cache – 该命名空间的缓存配置。
  • cache-ref – 引用其它命名空间的缓存配置。
  • resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
  • parameterMap – 老式风格的参数映射。此元素已被废弃,并可能在将来被移除!请使用行内参数映射。

3.1、模糊查询

<!-- 根据名称模糊查询 --> 
<select id="findByName" resultType="com.xyulu.entity.User" parameterType="String">
	select * from user where username like #{username}
</select>

<!--另一种配置方式-->
<select id="findByName" resultType="com.xyulu.entity.User" parameterType="String">
	select * from user where username like '%${value}%'
</select>
第一种方式传入字符串实参时,需要给定模糊查询的标识%,第二种模糊查询的写法,${value} 的写法是固定的

3.2、预处理 #{ }

使用 #{ } 告诉 MyBatis 创建一个预处理语句(PreparedStatement)参数,在 JDBC 中,这样的一个参数在 SQL 中会由一个“?”来标识,并被传递到一个新的预处理语句

// 近似的 JDBC 代码,非 MyBatis 代码...
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";

3.3、sql

这个元素可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用。 参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值,例如。

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

这个SQL 片段可以在其它语句中使用

<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/></include>,
    <include refid="userColumns"><property name="alias" value="t2"/></include>
  from some_table t1
    cross join some_table t2
</select>

3.4、参数

对于大多数简单的使用场景,你都不需要使用复杂的参数

3.4.1、字符串替换 ${ }

默认情况下,使用 #{ } 参数语法时,MyBatis 会创建 PreparedStatement 参数占位符,并通过占位符安全地设置参数(就像使用 ? 一样)。 这样做更安全,更迅速,通常也是首选做法,不过有时你就是想直接在 SQL 语句中直接插入一个 不转义 的字符串。
使用 ${ } , MyBatis 就不会修改或转义该字符串了

3.5、结果映射

3.5.1、简单映射

resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来

JavaBean 可以被映射到 ResultSet,就像映射到 HashMap 一样简单
<select id="selectUsers" resultType="com.someapp.model.User">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</select>
显式使用外部的 resultMap ,这也是解决列名不匹配的另外一种方式
<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name"/>
  <result property="password" column="hashed_password"/>
</resultMap>
<!--注意我们去掉了 resultType 属性-->
<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>

3.5.2、一对一查询(多对一)

<!-- 建立对应关系 --> 
<resultMap type="account" id="accountMap"> <id column="aid" property="id"/>
	<result column="uid" property="uid"/>
	<result column="money" property="money"/>
	<!-- 它是用于指定从表方的引用实体属性的 --> 
	<association property="user" javaType="user"> 
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="sex" property="sex"/>
		<result column="birthday" property="birthday"/>
		<result column="address" property="address"/>
	</association>
</resultMap>

3.5.3、一对多查询

<resultMap type="user" id="userMap"> 
	<id column="id" property="id"></id> <result column="username" property="username"/>
	<result column="address" property="address"/>
	<result column="sex" property="sex"/>
	<result column="birthday" property="birthday"/>
	<!--ofType 用于指定集合元素的数据类型--> 		  
	<collection property="accounts" ofType="account"> 
		<id column="aid" property="id"/>
		<result column="uid" property="uid"/>
		<result column="money" property="money"/>
	</collection>
</resultMap>

4、动态SQL

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

4.1、if

<select id="findActiveBlogWithTitleLike" resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果

And 还是很重要的,之前用“,” 写动态SQL的会出问题,当没有条件的的时候,会多出一个","

4.2、choose、when、otherwise

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

4.3、trim、where、set

<select id="findActiveBlogLike" resultType="Blog">
   SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

5、注解开发

看官网吧 Java API

Mybatis generator 代码生成器

可以参见这篇博客 Mybatis generator生成工具简单介绍

就先这样吧 后续有时间再补充,最后说一句 MybatisPlus 真香!!

Mybatis-Plus

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值