mybatis学习笔记

1.Mybatis学习笔记

1.CRUD(增删改查)

sqlSession.commit();(增删改需要提交事务)

1.namespace

namespace中的包名要和Dao/mapper接口的包名一致!;

<!--namespace会绑定一个对应的dao/mapper接口,相当于jpa里面的实现类impl-->

<mapper namespace="com.patarw.dao.UserDao">

 

id:就是namespace中对应的方法名

parameterType:参数类型

resultType:sql语句执行的返回值

<select id="findById" parameterType="int" resultType="com.patarw.pojo.User">

 

1.Mapper.xml文件里面增删改查的SQL语句的配置

(先编写mapper接口,在写接口的xml文件)

 

1.Insert(增)

<!--insert一个用户-->

<insert id="addUser" parameterType="com.patarw.pojo.User">
   insert into mybatis.user(id,name,phone) values (#{id},#{name},#{phone});
</insert>

 

2.Delete(删)

<!--删除一个用户-->

<delete id="deleteUserById" parameterType="int">
    delete from mybatis.user where id = #{id};
</delete>

 

3.Update(改)

<!--update一个用户-->

<update id="updateUser" parameterType="com.patarw.pojo.User">
    update mybatis.user set name=#{name},phone=#{phone}  where id=#{id};
</update>

 

4.Select(查)

<!--select查询sql语句 id是方法的名称 resultType是返回的数据类型-->

<select id="findById" parameterType="int" resultType="com.patarw.pojo.User">
select * from mybatis.user where id = #{id};
</select>

 

注意点!!增删改一定要提交事务:

sqlSession.commit();

 

5.like(模糊查询)

<!--模糊查询-->
<select id="getUserLike" resultType="com.patarw.pojo.User">
    select * from mybatis.user where name like #{value}
</select>

 

 List<User> userList = userDao.getUserLike("%wu%");
    for (User user : userList) {
        System.out.println(user);
    }

 

一定记得加在查询的时候加上 "%": "%wu%"

也可以在sql语句里面把#{value}变为"%"#{value}"%":

  select * from mybatis.user where name like "%"#{value}"%"

2.Mybatis核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
  • 每个配置必须按照顺序来写,不然会报错!!

 

configuration(配置)
  properties(属性)
  settings(设置)
  typeAliases(类型别名)
  typeHandlers(类型处理器)
  objectFactory(对象工厂)
  plugins(插件)
  environments(环境配置)
    environment(环境变量)
      transactionManager(事务管理器)
      dataSource(数据源)
  databaseIdProvider(数据库厂商标识)
  mappers(映射器)

 

环境配置(environments)

  • MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中 使用相同的 SQL 映射。有许多类似的使用场景。如开发者环境development和测试环境test;

 

  • 不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • 所以,如果你想连接两个数据库,就需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。而如果是三个数据库,就需要三个实例,依此类推,记起来很简单: 每个数据库对应一个 SqlSessionFactory 实例

 

  • 默认使用的环境 ID(比如:default="development")。
  • 每个 environment 元素定义的环境 ID(比如:id="development")。
  • 事务管理器(transactionManager)的配置(比如:type="JDBC")。
  • 数据源(dataSource)的配置(比如:type="POOLED")。

 

  • 提示如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器, 因为 Spring 模块会使用自带的管理器来覆盖前面的配置。

属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性都是可外部配置且可动态替换的,既可以在典型的java属性文件中配置:

    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;userSSL=true"/>
    <property name="username" value="root"/>
    <property name="password" value="1234"/>

也可以通过properties的元素的子元素来传递【db.properties】

 

下面我们来编写一个配置文件 db.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&userSSL=true
username=root
password=1234

然后再到核心配置文件里面引用(会优先引用外部配置文件):

<!--引入外部配置文件-->
<properties resource="db.properties"> </properties>

<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>

 

设置(settings)

  • 这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项的意图、默认值等。(具体内容可以去mybatis3官网上寻找)

 

一个配置完整的 settings 元素的示例如下:

<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone, hashCode,toString"/>
</settings>

 

映射器(mappers)

MapperRegistry:用来注册绑定我们的Mapper.xml文件

 

方式一

 <!-- 使用相对于类路径的资源引用 -->
 <mappers>
 <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
 <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
 <mapper resource="org/mybatis/builder/PostMapper.xml"/>
 </mappers>

 

方式二

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

注意点:

  • 接口和他的.xml配置文件必须同名
  • 接口和他的.xml配置文件必须在同一个包下

 

方式三

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>

注意点:

  • 接口和他的.xml配置文件必须同名
  • 接口和他的.xml配置文件必须在同一个包下

 

这些配置会告诉了 MyBatis 去哪里找映射文件(所以说还是老老实实使用第一种方法把。。)

 

3.分页

  • 为了减少数据的处理量

  • 使用Limit分页

    select * from user limit startIndex,pageSize;

startIndex:从第几个开始查

pageSize:每一页的数据数量

 

  • 当方法存在多个参数时所有的参数前面必须加上 @Param("id") 注解

@Param("id") int id,@Param("name") String name

 

关于@Param()注解的使用

  • 基本类型或者String类型的,则需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话可以忽略,但是最好是要加上
  • 我们在sql中引用的就是我们这里的 @Param()中设定的属性名

关于#{} 和 ${}的区别

  • #{}能防止sql注入,而${}不能,所以用#{}最好

 

4.多对一查询

<select id="getStudent" resultMap="studentTeacher">
    select * from student
</select>
<resultMap id="studentTeacher" type="com.patarw.pojo.Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" column="tid" javaType="com.patarw.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.patarw.pojo.Teacher">
    select * from teacher where id = #{id}
</select>

5.一对多查询

<select id="getTeacher" resultMap="TeacherStudent">
    select * from teacher
</select>
<resultMap id="TeacherStudent" type="com.patarw.pojo.Teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="student" column="id" ofType="com.patarw.pojo.Student" select="getStudent2"/>
</resultMap>
<select id="getStudent2" resultType="com.patarw.pojo.Student">
    select * from student where tid = #{id}
</select>

 

  • 关联-association【多对一】,集合-collection【一对多】
  • Javatype-用来指定实体类中属性的类型
  • ofType-用来指定映射到list或者集合中的pojo类型,泛型中的约束类型

 

6.动态sql

  • List findBlog(Map map);

  • 动态sql的重点就是下面的sql语句拼接了,还有其他的choose,when,otherwise我就不列举了,官方文档上都有

      <select id="findBlog" parameterType="map" resultType="com.patarw.pojo.Blog">
      select * from mybatis.blog where 1=1
      <if test="title != null">
          and title = #{title}
      </if>
      <if test="author != null">
          and author = #{author}
      </if>
      </select>
    

 

  • 这里使用到了map,现在还不是非常熟悉得记住这个用法 SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

      HashMap map = new HashMap(); //map的使用方法,非常重要!!
      map.put("author","黎展鹏");
      List<Blog> blogs = blogMapper.findBlog(map);
      System.out.println(blogs);
    
      sqlSession.close();
posted @ 2020-02-19 10:26  Patarw  阅读(111)  评论(0)    收藏  举报