美文网首页
MyBatis-入门

MyBatis-入门

作者: Dane_404 | 来源:发表于2019-07-20 10:50 被阅读0次

MyBatis是支持定制化SQL、存储过程以及高级映射的优秀持久层框架。MyBatis避免了几乎所有JDBC代码的手动设置参数已经获取结果集。MyBatis可以对配置和原生Map使用简单的XML或注解,将接口和Java的POJOs(普通的Java对象)映射成数据库中的记录。

MyBatis的引入和配置

在maven的pom.xml中引入:

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
 </dependencies>

然后在resource中新建dbconfig.properties和mybatis-config.xml文件:

dbconfig.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/Dane?characterEncoding=utf-8
username=root
password=root

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>

    <properties resource="dbconfig.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>
    <mappers>
        <mapper resource="mapper/userMapper.xml"></mapper>
    </mappers>
</configuration>

这样就引入了MyBatis,其中mappers是与我们开发的userMapper.xml是与我们开发的bean对应,下面会举例。

MyBatis的增删改查

引入和配置了MyBatis后,先简单的封装下MyBatis,把通用操作简单封装:

这里有几个注意的点,如果你的mybatis-config.xml文件不是放在resource下,那就必须给它全路径,获取SqlSession时,mybatis默认执行SQL后是不自动提交的,需要自动提交需要sqlSessionFactory.openSession(true):

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    public static SqlSession getSqlSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }

    public static void close(SqlSession sqlSession){
        if(sqlSession != null){
            sqlSession.close();
        }
    }
}

然后写个User对象:

public class User {

    private String id;
    private String name;
    private String password;
    private String account;
    
    ...
}

接着在resource中新建mapper文件夹,并在里面创建UserMapper.xml:

parameterType为传入参数类型,resultType为返回类型

<?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="dane">
    <select id="selectUser" resultType="com.dane.mybatis.bean.User">
    select * from User
  </select>

    <select id="insertUser" parameterType="com.dane.mybatis.bean.User">
    insert into user(account,password,name) values (#{account},#{password},#{name})
  </select>

    <select id="updateUser" parameterType="com.dane.mybatis.bean.User">
    update user set name = #{name} where id = #{id}
  </select>

    <select id="deleteUser" parameterType="int">
    delete from User where id = #{id}
  </select>
</mapper>

然后在mybatis-config.xml配置下:

 <mappers>
        <mapper resource="mapper/userMapper.xml"></mapper>
    </mappers>

接下来可以进行增删改查了:

sqlSession进行增删改查时,参数一对应的是UserMapper.xml中的命名空间和id,如查dane.selectUser

新建IUserDao以及实现类UserDaoImpl:

public interface IUserDao {

    public List<User> selectUsers();

    public void insertUsers(User user);

    public void updateUsers(User user);

    public void  deleteUsers(int id);
}
public class UserDaoImpl implements IUserDao {


    public List<User> selectUsers() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        List<User> users = sqlSession.selectList("dane.selectUser");

        sqlSession.commit();;
        MyBatisUtil.close(sqlSession);
        return users;
    }

    public void insertUsers(User user) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        sqlSession.insert("dane.insertUser",user);
        sqlSession.commit();;
        MyBatisUtil.close(sqlSession);
    }

    public void updateUsers(User user) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        sqlSession.update("dane.updateUser",user);
        sqlSession.commit();
        MyBatisUtil.close(sqlSession);

    }

    public void deleteUsers(int id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        sqlSession.delete("dane.deleteUser",id);
        sqlSession.commit();
        MyBatisUtil.close(sqlSession);
    }

然后进行增删改查测试

public class MyBatisTest {


    @Test
    public void selectUser(){

        IUserDao userDao = new UserDaoImpl();
        List<User> users = userDao.selectUsers();
        for (User user : users) {
            System.out.println(user.getId());
            System.out.println(user.getName());
            System.out.println(user.getAccount());
            System.out.println(user.getPassword());

        }

    }

    @Test
    public void insertUser(){

        IUserDao userDao = new UserDaoImpl();
        User user = new User();
        user.setAccount("Dane小号");
        user.setPassword("123456");
        user.setName("Dane小号");
        userDao.insertUsers(user);

    }

    @Test
    public void updateUser(){

        IUserDao userDao = new UserDaoImpl();
        User user=new User();
        user.setId(2);
        user.setName("dane6666");
        userDao.updateUsers(user);

    }

    @Test
    public void deleteUser(){

        IUserDao userDao = new UserDaoImpl();
        userDao.deleteUsers(2);

    }
}

Mybatis Mapper代理

在上面的例子中,我们需要自己实现IUserDao,使用Mapper代理,可以无需自己实现。

首先,看修改后的UserMapper.xml,命名空间必须是IUserDao的引用路径,每个select的id必须是IUserDao的方法,包括参数要一一对应。

<?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.dane.mybatis.dao.IUserDao">
    <select id="selectUsers" resultType="com.dane.mybatis.bean.User">
    select * from User
  </select>

    <select id="insertUsers" parameterType="com.dane.mybatis.bean.User">
    insert into user(account,password,name) values (#{account},#{password},#{name})
  </select>

    <select id="updateUsers" parameterType="com.dane.mybatis.bean.User">
    update user set name = #{name} where id = #{id}
  </select>

    <select id="deleteUsers" parameterType="int">
    delete from User where id = #{id}
  </select>
</mapper>

然后看下使用,查询为例:

   SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
   IUserDao userDao = sqlSession.getMapper(IUserDao.class);
   List<User> users = userDao.selectUsers();
   for (User user : users) {
       System.out.println(user.getId());
       System.out.println(user.getName());
       System.out.println(user.getAccount());
       System.out.println(user.getPassword());

   }
   MyBatisUtil.close(sqlSession);

Mybatis配置Log框架

首先要了解下slf4j日志框架并没真正的实现日志记录,而是一个日志标准或者说是抽象,它提供日志接口和提供获取具体日志对象的方法,所以真正实现日志的还要靠log4j等。

在Mybatis中只需要想pom.xml引入并在resource配置log4j.properties即可:

<!--slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--slf4j到log4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>

log4j.properties

log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=hx.log

log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

log4j.logger.com.codefutures=DEBUG
然后运行代码,会有如下图: image.png

使用MyBatis注解的方式

上面的SQL语句是放在UserMapper.xml文件中,MyBatis也可以使用注解的方式:

public interface IUserDao2 {

    @Select(" select * from User")
    public List<User> selectUsers();

    @Insert("insert into user(account,password,name) values (#{account},#{password},#{name})")
    public void insertUsers(User user);

    @Update("update user set name = #{name} where id = #{id}")
    public void updateUsers(User user);

    @Delete("delete from User where id = #{id}")
    public void  deleteUsers(int id);
}

然后在mybatis-config.xml中配置,注意是class

 <mappers>
        <mapper class="com.dane.mybatis.dao.IUserDao2"></mapper>
    </mappers>

然后就可以测试啦,查询为例:

  SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
  IUserDao2 userDao = sqlSession.getMapper(IUserDao2.class);
  List<User> users = userDao.selectUsers();
  for (User user : users) {
      System.out.println(user.getId());
      System.out.println(user.getName());
      System.out.println(user.getAccount());
      System.out.println(user.getPassword());
  }
   MyBatisUtil.close(sqlSession);

MyBatis输入输出参数进一步了解

假设客户端上来的数据封装成UserQueryVo,除了有User信息外,还有其他信息:

public class UserVo {

   private UserPo user;

   private List<Integer> orderIds;

   ....
}

然后之前的User对象,改名成UserPo,PO表示持久对象,VO表示值对象:

package com.dane.mybatis.bean;

public class UserPo {

    private int id;
    private String name;
    private String password;
    private String account;

    ....
}

然后看下MyBatis这种情况参数怎么处理,这里我使用注解的方式:


public interface IUserDao3 {

    @Select("select account from User where name=#{user.name}")
    public List<UserPo> selectUsers(UserVo userVo);

}

别忘了配置Mapper:

 <mappers>
        <mapper class="com.dane.mybatis.dao.IUserDao3"></mapper>
 </mappers>

然后测试下:

 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
 IUserDao3 userDao = sqlSession.getMapper(IUserDao3.class);
 UserVo userVo = new UserVo();
 UserPo user1 = new UserPo();
 user1.setName("dane");
 userVo.setUser(user1);
 List<User> users = userDao.selectUsers(userVo);
 for (User user : users) {
     System.out.println(user.getAccount());
 }
 MyBatisUtil.close(sqlSession);

接下来是Map的方式,通过HashMap封装请求信息

@Select("select id,account from User where name=#{name} 
              and password=#{password}")    
public List<UserPo> selectUsersByHashMap(HashMap hashMap);

测试下:

 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
 IUserDao3 userDao = sqlSession.getMapper(IUserDao3.class);
 HashMap map = new HashMap();
 map.put("name","dane");
 map.put("password","123456");
 List<User> users = userDao.selectUsersByHashMap(map);
 for (User user : users) {
     System.out.println(user.getAccount());
 }
 MyBatisUtil.close(sqlSession);

MyBatis表名与实体属性不一样的映射方法

假设数据库表Message字段为_id、_content,我们的实体类属性为id、content

SQL语句解决

@Select("SELECT _id id,_content content from Message where _id=#{id}")
public Message findMessageById(int id);
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
IUserDao3 userDao = sqlSession.getMapper(IUserDao3.class);
Message message  = userDao.findMessageById(1);
System.out.println(message.getContent());
MyBatisUtil.close(sqlSession);

配置映射解决

 @Select("SELECT _id ,_username,_psw,_sex FROM muser WHERE _id=#{id}")
 @Results({
        @Result(column="_id", property="id", id=true),
        @Result(column="_username", property="username"),
        @Result(column="_psw", property="psw"),
        @Result(column="_sex", property="sex")})
 public UserPo findUserById(int id);

非注解的方式:

<?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.dane.mybatis.dao.IUserDao3">

    <resultMap id="rst" type="Message">
        <id column="_id" property="id"/>
        <result column="_content" property="content"/>
    </resultMap>
    <select id="findMessageById" parameterType="int" resultMap="rst">
        select _id ,_content from Message where _id=#{id}
    </select>
</mapper>

MyBatis一对一表查询

根据User的name,找出User和对应的Home

public class User {

    private int id;
    private String name;
    private String password;
    private String mobile;
    private int home_id;
    private  Home home;

    .....
}

方法一:分开查询

@Select("select * from User where name = #{name}")
@Results(@Result(property = "home",column = "home_id",
        one = @One(select = "com.dane.mybatis.dao.IUserDao4.getHome"
)))
User getUser(String name);

@Select("select * from Home where id = #{id}")
Home getHome(int id);
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
IUserDao4 userDao = sqlSession.getMapper(IUserDao4.class);
User user = userDao.getUser("Dane");
System.out.println(user);
MyBatisUtil.close(sqlSession);

非注解方式:

<?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.dane.mybatis.dao.IUserDao4">

    <select id="getUser" parameterType="string" resultMap="rst1">
        SELECT * FROM User WHERE name=#{name};
    </select>

    <resultMap id="rst1" type="com.dane.mybatis.bean.User">
        <id property="id" column="id"></id>
        <result property="mobile" column="mobile"/>
        <result property="password" column="password"/>
        <result property="name" column="name"/>
        <result property="home_id" column="home_id"/>
        <association property="home" column="home_id" select="getHome"/>
    </resultMap>

    <select id="getHome" parameterType="int" resultType="com.dane.mybatis.bean.Home">
        SELECT * FROM Home WHERE id=#{id};
    </select>
</mapper>

方法二:联合查询
首先写好resultMap,并在mybatis-config中配置:

<?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.dane.mybatis.dao.IUserDao4">
  <!--<select id="getUser" parameterType="string" resultMap="rst1">-->
        <!--SELECT u.*,h.* FROM user u, home h WHERE h.hid=u.home_id AND u.name=#{name};-->
    <!--</select>-->

  <resultMap id="rst1" type="com.dane.mybatis.bean.User">
    <id property="id" column="id"></id>
    <result property="name" column="name"/>
    <result property="mobile" column="mobile"/>
    <result property="password" column="password"/>

    <association property="home" column="home_id" javaType="com.dane.mybatis.bean.Home">
      <id property="id" column="hid"></id>
      <result property="name" column="hname"></result>
    </association>
  </resultMap>

</mapper>
 @Select("select u.*, h.* from User u,Home h where u.name = #{name} and h.hid = u.home_id")
 @ResultMap("rst1")
 User getUser(String name);

MyBatis一对多表查询

根据hid查询出Home以及Home下所有User

分开查询

@Select("select * from Home where hid = #{id}")
@Results({
        @Result(property = "id",column = "hid",id = true),
        @Result(property = "name",column = "hname"),
        @Result(
        property = "users",column = "hid",
        many = @Many(select = "com.dane.mybatis.dao.IUserDao4.getUsers"
))})
Home getHome(int id);

@Select("select * from user where home_id = #{home_id}")
List<User> getUsers(int home_id);

非注解方式只需要把association换成collection

<?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.dane.mybatis.dao.IUserDao4">

    <select id="getHome" parameterType="int" resultMap="rst1">
        SELECT * FROM home WHERE hid=#{id};
    </select>

    <resultMap id="rst1" type="com.dane.mybatis.bean.Home">
        <id property="id" column="hid"></id>
        <result property="name" column="hname"/>
        <collection property="users" column="hid" select="getUsers"/>
    </resultMap>

    <select id="getUsers" parameterType="int" resultType="com.dane.mybatis.bean.Home">
        SELECT * FROM User WHERE home_id=#{id};
    </select>

联合查询

注意除了association换成collection,javaType换成ofType

<mapper namespace="com.dane.mybatis.dao.IUserDao4">
  <!--<select id="getHome" parameterType="int" resultMap="rst1">-->
        <!--SELECT u.*,h.* FROM user u, home h WHERE h.hid=#{id} AND u.home_id=h.hid};-->
    <!--</select>-->

  <resultMap id="rst1" type="com.dane.mybatis.bean.Home">
    <id property="id" column="hid"></id>
    <result property="name" column="hname"/>
    
    <collection property="users" column="hid" ofType="com.dane.mybatis.bean.User">
      <id property="id" column="id"></id>
      <result property="name" column="name"></result>
      <result property="mobile" column="mobile"></result>
      <result property="password" column="password"></result>
      <result property="home_id" column="home_id"></result>
    </collection>
  </resultMap>

</mapper>
 @Select("select h.*,u.* from Home h ,User u where hid = #{id} and h.hid = u.home_id")
 @ResultMap("rst1")
 Home getHome(int id);

MyBatis延迟加载

所谓的延迟加载,就是用到才去查询,比如:一对多查询,先查出了Home,home里面的users还没用到,MyBatis不会先去查询,等到我们用到getUsers时,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>
    <properties resource="dbconfig.properties"></properties>
    <settings>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--关闭积极加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    ......
</configuration>

MyBatis配置参数路径或别名

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

MyBatis动态Sql

where

<?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.dane.mybatis.dao.IUserDao4">
  <select id="getUser" parameterType="int" resultType="User">
        SELECT * FROM user
    <where>
      <if test="name != null">
        and name = #{name}
      </if>
      <if test="mobile != null">
        and mobile = #{mobile}
      </if>
    </where>
  </select>
</mapper>

注解方式

 @Select("<script>select * from user " +
            "<if test=\"name !=null\">where name = #{name}</if> " +
            "<if test =\"mobile !=null\"> and mobile = #{mobile}</if>" +
            "</script>")
 User getUser(User user);

set

<update id="updateUser" parameterType="User">
        UPDATE User
        <set>
            <if test="name !=null">
                name=#{name},
            </if>
            <if test="password !=''">
                password=#{password},
            </if>
        </set>
        <where>
            <if test="id !=0">
                id=#{id}
            </if>
        </where>
 </update>

注解方式

@Select("<script>update user " +
            "<set>"+
            "<if test=\"name !=null\"> name = #{name},</if> " +
            "<if test =\"password !=null\"> password = #{password},</if>" +
            "</set>"+
            "<where><if test=\"id !=0\">id = #{id}</if></where>"+
            "</script>")
User updateUser(User user);

foreach

<select id="getUsersByIds" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id IN
      <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
          #{id}
      </foreach>
</select>

<select id="getUserByListIds" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id IN
        <foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
            #{id}
        </foreach>
</select>

MyBatis调用存储过程

DELIMITER $
CREATE PROCEDURE dane.student_count(IN sex INT, OUT count INT)
BEGIN
IF sex=0 THEN
SELECT COUNT(*) FROM dane.User WHERE User.sex='女' INTO count; ELSE
SELECT COUNT(*) FROM dane.student WHERE User.ssex='男' INTO count; END IF;
END
$
<select id="getUserCountBySex" parameterMap="pmap"
statementType="CALLABLE">
CALL dane.user_count(?,?);
</select>
<parameterMap id="pmap" type="java.util.Map">
      <parameter property="sex" jdbcType="INTEGER" mode="IN">
      </parameter>
      <parameter property="count" jdbcType="INTEGER" mode="OUT">
      </parameter>
</parameterMap>

MyBatis缓存

MyBatis提供了一级和二级两种缓存,当进行增删改时,一级二级缓存都会被清空。

一级缓存基于PerpetualCache的HashMap本地缓存,其存储作用域为Session,当Session flush或close之后,该session中所有cache就将清空,一级缓存默认开启

二级缓存也是基于PerpetualCache的HashMap本地缓存,不过其存储作用域是Mapper,二级缓存默认不开启。要开启二级缓存,只需要在Mapper.xml中配置cache:

<?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.dane.mybatis.dao.IUserDao4">

  <!--eviction 缓存回收策略
           LRU:最少使用原则,移除最长时间不使用的对象;
           FIFO:先进先出原则,按照对象进入缓存顺序进行回收;
           SOFT:软引用;
           WEAK:弱引用。
      flushInterval:刷新时间间接,不设置的话只有进行增删改才会刷新
      size:缓存的大小,默认1024个
      readOnly:如果是true,所有相同的sql语句返回的是用一个对象,可以提搞性能,但并发时不安全
               如果是false,则相同的sql,后面访问的是cache的clone副本。
    -->
  <cache eviction="LRU" flushInterval="1000" size="1024" readOnly="true" />

  <!-- select 可以使用useCache指定是否使用缓存-->
  <select id="" useCache="false"></select>

  <!-- 增删改 可以使用flushCache指定是否刷新缓存-->
  <update id="" flushCache="false"></update>

</mapper>

自定义缓存
实现MyBatis的Cache接口(具体自己实现),然后配置即可:

 <cache type="com.dane.mybatis.MyCache" />

MyBaits配置package

之前我们每写一个Mapper,都需要在MyBatis-config中去配置,可以采用package进行全局配置:

<mappers>
    <package name="com.dane.mybatis.mapper"/>
</mappers>

如果报找不到mapper,在pom.xml下配置:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

MyBatis自动生成插件

MyBatis的org.mybatis.generator插件可以自动生成Mapper和Model代码:

添加依赖被配置resource:

<build>
    <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis‐generator‐maven‐plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
            </plugins>
    </pluginManagement>

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

在resource下新建generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--导入属性配置-->
    <properties resource="dbconfig.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置-->
    <classPathEntry location="/Users/czd/.m2/repository/mysql/mysql-connector-java/8.0.15/mysql-connector-java-8.0.15.jar"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>


        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="${driver}"
                connectionURL="${url}"
                userId="${username}"
                password="${password}">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="com.dane.mybatis.model"
                            targetProject="src/main/java">

            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="com.dane.mybatis.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator targetPackage="com.dane.mybatis.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <table tableName="User" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

然后添加Configuration,commod line 为mybatis‐generator:generate ‐e


image.png

然后跑一下,就自动生成代码了:


image.png

相关文章

  • MyBatis-入门

    MyBatis是支持定制化SQL、存储过程以及高级映射的优秀持久层框架。MyBatis避免了几乎所有JDBC代码的...

  • 深入浅出Mybatis-入门

    写在系列前 这学期在上陈昊鹏老师的企业级应用系统体系架构这门课,载体为Java EE。这个系列用来记录Java W...

  • 【mybatis-高级篇】

    mybatis-高级篇 一、mybatis原理 Mybatis的四大对象ExecutorParameterHand...

  • Mybatis-Plus基础

    Mybatis Plus基础 1、mybatis-主键生成策略 自动增长 :AUTO Increment(不方便分...

  • MyBatis-框架简单介绍和入门程序

    mybatis 是什么? mybatis是一个持久层的框架,是Apache下的顶级项目。mybatis可在GitH...

  • 深入浅出MyBatis-快速入门

    简介MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apache sof...

  • mybatis整合spring

    mybatis篇 mybatis-独立使用 mybatis之TypeHandler mybatis一级缓存原理 m...

  • mybatis插件原理解析

    mybatis篇 mybatis-独立使用 mybatis之TypeHandler mybatis一级缓存原理 m...

  • mybatis-独立使用

    mybatis篇 mybatis-独立使用 mybatis之TypeHandler mybatis一级缓存原理 m...

  • mybatis之TypeHandler

    mybatis篇 mybatis-独立使用 mybatis之TypeHandler mybatis一级缓存原理 m...

网友评论

      本文标题:MyBatis-入门

      本文链接:https://www.haomeiwen.com/subject/ntafkctx.html