0


Mybatis框架知识整理

Mybatis简介

学习框架前,先梳理原始JDBC如何操作数据库

原始JDBC操作

查询数据

引入依赖

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency></dependencies>

测试查询数据
测试用表
在这里插入图片描述

数据库表映射类

packagecom.jtyhnet.domain;publicclassAccount{privateint id;privateString name;privatefloat money;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicfloatgetMoney(){return money;}publicvoidsetMoney(float money){this.money = money;}@OverridepublicStringtoString(){return"account{"+"id="+ id +", name='"+ name +'\''+", money="+ money +'}';}}

测试代码

importcom.jtyhnet.domain.Account;importorg.junit.Test;importjava.sql.*;publicclassJDBCTest1{@Testpublicvoidtest1()throwsClassNotFoundException,SQLException{//注册驱动Class.forName("com.mysql.jdbc.Driver");//获得连接Connection connection =DriverManager.getConnection("jdbc:mysql:///test","root","root");//获得statementPreparedStatement preparedStatement = connection.prepareStatement("select * from account");//执行查询ResultSet resultSet = preparedStatement.executeQuery();//遍历结果集while(resultSet.next()){//封装实体Account account =newAccount();
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getFloat("money"));//实体封装完成System.out.println(account);}//释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();}}

在这里插入图片描述

插入数据

@Testpublicvoidtest2()throwsClassNotFoundException,SQLException{Account account =newAccount();
        account.setName("wangwu");
        account.setMoney(6000);//注册驱动Class.forName("com.mysql.jdbc.Driver");//获得连接Connection connection =DriverManager.getConnection("jdbc:mysql:///test","root","root");//获得statementPreparedStatement preparedStatement = connection.prepareStatement("insert into account(id,name,money) values (?,?,?)");//设置占位符参数
        preparedStatement.setInt(1,account.getId());
        preparedStatement.setString(2,account.getName());
        preparedStatement.setFloat(3,account.getMoney());//执行更新操作
        preparedStatement.executeUpdate();//释放资源
        preparedStatement.close();
        connection.close();}

在这里插入图片描述

原始JDBC操作分析

原始jdbc开发存在的问题如下:
① 数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能
② sql 语句在代码中硬编码,造成代码不易维护,实际应用 sql 变化的可能较大,sql 变动需要改变java代码。
③ 查询操作时,需要手动将结果集中的数据手动封装到实体中。插入操作时,需要手动将实体的数据设置到sql语句的占位符位置
应对上述问题给出的解决方案:
① 使用数据库连接池初始化连接资源
② 将sql语句抽取到xml配置文件中
③ 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射

Mybatis简介

  • mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
  • mybatis通过xml或注解的方式将要执行的各种 statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。
  • 最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc进行了封装,屏蔽了jdbc api 底层访问细节,使我们不用与jdbc api打交道,就可以完成对数据库的持久化操作。

快速入门

MyBatis开发步骤:
① 添加MyBatis的坐标
② 创建user数据表
③ 编写User实体类
④ 编写映射文件UserMapper.xml
⑤ 编写核心文件SqlMapConfig.xml
⑥ 编写测试类

依赖导入

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency></dependencies>

为查看详细日志,resources下新建log4j.properties配置文件

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

创建测试用表
在这里插入图片描述

创建实体类

packagecom.jtyhnet.domain;publicclassUser{privateint id;privateString username;privateString password;@OverridepublicStringtoString(){return"User{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+'}';}publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}}

编写映射文件UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="userMapper"><selectid="findAll"resultType="com.jtyhnet.domain.User">
        select * from USER
    </select></mapper>

编写mybatis核心配置文件SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql:///test"/><propertyname="username"value="root"/><propertyname="password"value="root"/></dataSource></environment></environments><mappers><mapperresource="com/jtyhnet/mapper/UserMapper.xml"/></mappers></configuration>

进行测试

importcom.jtyhnet.domain.User;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Test;importjava.io.IOException;importjava.io.InputStream;importjava.util.List;publicclassMybatisTest1{@Testpublicvoidtest1()throwsIOException{//加载核心配置文件InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");//获得SqlSession工厂对象SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);//获得sqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//执行sql语句List<User> userList = sqlSession.selectList("userMapper.findAll");//打印结果System.out.println(userList);//释放资源
        sqlSession.close();}}

在这里插入图片描述

MyBatis的映射文件概述

在这里插入图片描述

MyBatis的增删改查操作

MyBatis的插入数据操作

UserMapper.xml中添加

<insertid="add"parameterType="com.jtyhnet.domain.User">
        insert into user values (#{id},#{username},#{password})
    </insert>

测试代码

@Testpublicvoidtest2()throwsIOException{User user =newUser();
        user.setUsername("lisi");
        user.setPassword("12233");InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();int insert = sqlSession.insert("userMapper.add",user);System.out.println("userMapper.add : "+insert);
        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述
查询数据库确认插入成功
在这里插入图片描述

  • 插入操作注意问题 • 插入语句使用insert标签 • 在映射文件中使用parameterType属性指定要插入的数据类型 • Sql语句中使用#{实体属性名}方式引用实体中的属性值 • 插入操作使用的API是sqlSession.insert(“命名空间.id”,实体对象); • 插入操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务,即sqlSession.commit()

MyBatis的修改数据操作

UserMapper.xml中添加

<updateid="update"parameterType="com.jtyhnet.domain.User">
        update user set username=#{username},password=#{password} where id = #{id}
    </update>
@Testpublicvoidtest3()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();User user =newUser();
        user.setId(3);
        user.setUsername("lisi");
        user.setPassword("12222");int update = sqlSession.update("userMapper.update", user);System.out.println("更新条数:"+update);

        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述
查询数据库确认数据完成更新
在这里插入图片描述

  • 修改操作注意问题 • 修改语句使用update标签 • 修改操作使用的API是sqlSession.update(“命名空间.id”,实体对象);

MyBatis的删除数据操作

<deleteid="delete"parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>
@Testpublicvoidtest4()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();int delete = sqlSession.delete("userMapper.delete",3);System.out.println("删除条数:"+delete);
        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述
查询数据库确认数据已删除
在这里插入图片描述

  • 删除操作注意问题 • 删除语句使用delete标签 • Sql语句中使用#{任意字符串}方式引用传递的单个参数 • 删除操作使用的API是sqlSession.delete(“命名空间.id”,Object);

增删改查配置小结

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="userMapper"><!--查--><selectid="findAll"resultType="com.jtyhnet.domain.User">
        select * from USER
    </select><!--增--><insertid="add"parameterType="com.jtyhnet.domain.User">
        insert into user values (#{id},#{username},#{password})
    </insert><!--改--><updateid="update"parameterType="com.jtyhnet.domain.User">
        update user set username=#{username},password=#{password} where id = #{id}
    </update><!--删--><deleteid="delete"parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete></mapper>
//查List<User> userList = sqlSession.selectList("userMapper.findAll");//增int insert = sqlSession.insert("userMapper.add",user);
sqlSession.commit();//删int update = sqlSession.update("userMapper.update", user);
sqlSession.commit();//改int delete = sqlSession.delete("userMapper.delete",3);
sqlSession.commit();

MyBatis核心配置文件概述

核心配置文件层级关系
在这里插入图片描述

MyBatis常用配置解析

environments标签

数据库环境的配置,支持多环境配置
在这里插入图片描述
其中,事务管理器(transactionManager)类型有两种:

  • JDBC:这个配置就是直接使用了JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
  • MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将closeConnection 属性设置为 false 来阻止它默认的关闭行为。

其中,数据源(dataSource)类型有三种:

  • UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。
  • POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。
  • JNDI:这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置 一个 JNDI 上下文的引用。

mapper标签

该标签的作用是加载映射的,加载方式有如下几种:

  • 使用相对于类路径的资源引用,例如:<mapper resource=“org/mybatis/builder/AuthorMapper.xml”/>
  • 使用完全限定资源定位符(URL),例如:<mapper url=“file:///var/mappers/AuthorMapper.xml”/>
  • 使用映射器接口实现类的完全限定类名,例如:<mapper class=“org.mybatis.builder.AuthorMapper”/>
  • 将包内的映射器接口实现全部注册为映射器,例如:<package name=“org.mybatis.builder”/>

Properties标签

实际开发中,习惯将数据源的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的properties文件

在这里插入图片描述

typeAliases标签

类型别名是为Java 类型设置一个短的名字。原来的类型名称配置如下

<selectid="findAll"resultType="com.jtyhnet.domain.User">
        select * from USER
    </select>

配置typeAliases,为com.jtyhnet.domain.User定义别名为user

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="jdbc.properties"/><typeAliases><typeAliastype="com.jtyhnet.domain.User"alias="user"/></typeAliases><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><mappers><mapperresource="com/jtyhnet/mapper/UserMapper.xml"/></mappers></configuration>

使用别名配置mapper

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="userMapper"><!--查--><selectid="findAll"resultType="user">
        select * from USER
    </select><!--增--><insertid="add"parameterType="com.jtyhnet.domain.User">
        insert into user values (#{id},#{username},#{password})
    </insert><!--改--><updateid="update"parameterType="com.jtyhnet.domain.User">
        update user set username=#{username},password=#{password} where id = #{id}
    </update><!--删--><deleteid="delete"parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete></mapper>

执行查询测试
在这里插入图片描述
上面我们是自定义的别名,mybatis框架已经为我们设置好的一些常用的类型的别名
别名数据类型stringStringlongLongintIntegerdoubleDoublebooleanBoolean… …… …

知识小结

核心配置文件常用配置:
1、properties标签:该标签可以加载外部的properties文件

<propertiesresource="jdbc.properties"/>

2、typeAliases标签:设置类型别名

<typeAliases><typeAliastype="com.jtyhnet.domain.User"alias="user"/></typeAliases>

3、mappers标签:加载映射配置

<mappers><mapperresource="com/jtyhnet/mapper/UserMapper.xml"/></mappers>

4、environments标签:数据源环境配置标签

<environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments>

MyBatis相应API

SqlSession工厂构建器SqlSessionFactoryBuilder

常用API:SqlSessionFactory build(InputStream inputStream)
通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象

//加载核心配置文件InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");//获得SqlSession工厂对象SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);

其中, Resources 工具类,这个类在 org.apache.ibatis.io 包中。Resources 类帮助你从类路径下、文件系统或一个 web URL 中加载资源文件。

SqlSession工厂对象SqlSessionFactory

SqlSessionFactory 有多个个方法创建 SqlSession 实例。常用的有如下两个:
方法解释openSession()会默认开启一个事务,但事务不会自动提交,也就意味着需要手动提交该事务,更新操作数据才会持久化到数据库中openSession(boolean autoCommit)参数为是否自动提交,如果设置为true,那么不需要手动提交事务

SqlSession会话对象

SqlSession 实例在 MyBatis 中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。
执行语句的方法主要有:

<T>TselectOne(String statement,Object parameter)<E>List<E>selectList(String statement,Object parameter)intinsert(String statement,Object parameter)intupdate(String statement,Object parameter)intdelete(String statement,Object parameter)

操作事务的方法主要有:

voidcommit()voidrollback()

MyBatis的Dao层实现方式

传统开发方式

packagecom.jtyhnet.dao;importcom.jtyhnet.domain.User;importjava.util.List;publicinterfaceUserDao{List<User>findAll()throwsException;}
packagecom.jtyhnet.dao.impl;importcom.jtyhnet.dao.UserDao;importcom.jtyhnet.domain.User;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importjava.io.InputStream;importjava.util.List;publicclassUserDaoImplimplementsUserDao{@OverridepublicList<User>findAll()throwsException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> userList = sqlSession.selectList("userMapper.findAll");return userList;}}

测试

@Testpublicvoidtest5()throwsException{UserDao userDao =newUserDaoImpl();List<User> userList = userDao.findAll();System.out.println(userList);}

在这里插入图片描述

代理开发方式

采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。
Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的全限定名相同
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

接口类

packagecom.jtyhnet.dao;importcom.jtyhnet.domain.User;importjava.io.IOException;importjava.util.List;publicinterfaceUserDao{List<User>findAll()throwsIOException;UserfindById(int id);}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.jtyhnet.dao.UserDao"><selectid="findAll"resultType="user">
        select * from user
    </select><selectid="findById"parameterType="int"resultType="user">
        select * from user where id = #{id}
    </select></mapper>
@Testpublicvoidtest21()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);List<User> userList = userDaoMapper.findAll();System.out.println(userList);System.out.println("------");User user1 = userDaoMapper.findById(1);System.out.println(user1);}

在这里插入图片描述
在这里插入图片描述
传统方式实现接口
代理方式在xml配置文件中对应接口类配置映射

MyBatis映射文件深入

动态sql语句

Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。

动态 SQL 之<if>

我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

接口类

packagecom.jtyhnet.dao;importcom.jtyhnet.domain.User;importjava.io.IOException;importjava.util.List;publicinterfaceUserDao{List<User>findAll()throwsIOException;UserfindById(int id);UserfindByCondition(User user);}

mapper配置

<selectid="findByCondition"parameterType="user"resultType="user">
        select * from user
        <where><iftest="id!=0">
                and id = #{id}
            </if><iftest="username!=null">
                and username = #{username}
            </if></where></select>

测试代码

@Testpublicvoidtest22()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);User user =newUser();
        user.setId(1);
        user.setUsername("zhangsan");User user1 = userDaoMapper.findByCondition(user);System.out.println(user1);}

在这里插入图片描述
改变条件再次测试

@Testpublicvoidtest22()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);User user =newUser();
        user.setId(1);//user.setUsername("zhangsan");User user1 = userDaoMapper.findByCondition(user);System.out.println(user1);}

在这里插入图片描述
可见查询语句随参数的改变动态变化

动态 SQL 之<foreach>

循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。

接口增加

List<User>findByIds(List<Integer> ids);

mapper增加

<selectid="findByIds"parameterType="list"resultType="user">
        select * from user
        <where><foreachcollection="list"open="id in ("close=")"item="id"separator=",">
                #{id}
            </foreach></where></select>
@Testpublicvoidtest23()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);ArrayList<Integer> idList =newArrayList<>();
        idList.add(1);
        idList.add(4);
        idList.add(5);List<User> userList = userDaoMapper.findByIds(idList);System.out.println(userList);}

在这里插入图片描述

在这里插入图片描述
foreach标签的属性含义如下:
<foreach>标签用于遍历集合,它的属性:
• collection:代表要遍历的集合元素,注意编写时不要写#{}
• open:代表语句的开始部分
• close:代表结束部分
• item:代表遍历集合的每个元素,生成的变量名
• sperator:代表分隔符

SQL片段抽取

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<sqlid="selectAllUser">select * from user</sql><includerefid="selectAllUser"/>
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.jtyhnet.dao.UserDao"><sqlid="selectAllUser">select * from user</sql><selectid="findAll"resultType="user"><includerefid="selectAllUser"/></select><selectid="findById"parameterType="int"resultType="user"><includerefid="selectAllUser"/> where id = #{id}
    </select><selectid="findByCondition"parameterType="user"resultType="user"><includerefid="selectAllUser"/><where><iftest="id!=0">
                and id = #{id}
            </if><iftest="username!=null">
                and username = #{username}
            </if></where></select><selectid="findByIds"parameterType="list"resultType="user"><includerefid="selectAllUser"/><where><foreachcollection="list"open="id in ("close=")"item="id"separator=",">
                #{id}
            </foreach></where></select></mapper>

MyBatis核心配置文件深入

typeHandlers标签

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。下表描述了一些默认的类型处理器(截取部分)。

在这里插入图片描述
你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。具体做法为:实现org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类org.apache.ibatis.type.BaseTypeHandler, 然后可以选择性地将它映射到一个JDBC类型。例如需求:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的毫秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。

开发步骤:
① 定义转换类继承类BaseTypeHandler
② 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
③ 在MyBatis核心配置文件中进行注册
④ 测试转换是否正确

创建测试用表

CREATETABLE userinfo (
    id INTNOTNULLauto_increment,     
    username VARCHAR(50),    
    password VARCHAR(50),        
    birthday VARCHAR(50),PRIMARYKEY( id ));insertinto userinfo values(null,'zhangsan','123','1640784746140');

创建实体类

packagecom.jtyhnet.domain;importjava.util.Date;publicclassUserinfo{privateint id;privateString username;privateString password;privateDate birthday;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicDategetBirthday(){return birthday;}publicvoidsetBirthday(Date birthday){this.birthday = birthday;}@OverridepublicStringtoString(){return"Userinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", birthday="+ birthday +'}';}}

插入数据接口方法

packagecom.jtyhnet.dao;importcom.jtyhnet.domain.Userinfo;publicinterfaceUserinfoDao{voidadd(Userinfo userinfo);}

定义转换类

packagecom.jtyhnet.typeHandler;importorg.apache.ibatis.type.BaseTypeHandler;importorg.apache.ibatis.type.JdbcType;importjava.sql.CallableStatement;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Date;publicclassMyDateTypeHandlerextendsBaseTypeHandler<Date>{@OverridepublicvoidsetNonNullParameter(PreparedStatement preparedStatement,int i,Date date,JdbcType jdbcType)throwsSQLException{
        preparedStatement.setString(i,date.getTime()+"");}@OverridepublicDategetNullableResult(ResultSet resultSet,String s)throwsSQLException{returnnewDate(resultSet.getLong(s));}@OverridepublicDategetNullableResult(ResultSet resultSet,int i)throwsSQLException{returnnewDate(resultSet.getLong(i));}@OverridepublicDategetNullableResult(CallableStatement callableStatement,int i)throwsSQLException{return callableStatement.getDate(i);}}

mybatis核心配置类
添加userinfo别名,<typeHandlers>注册自定义转换类

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="jdbc.properties"/><typeAliases><typeAliastype="com.jtyhnet.domain.User"alias="user"/><typeAliastype="com.jtyhnet.domain.Userinfo"alias="userinfo"/></typeAliases><typeHandlers><typeHandlerhandler="com.jtyhnet.typeHandler.MyDateTypeHandler"/></typeHandlers><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><mappers><mapperresource="com/jtyhnet/mapper/UserDaoMapper.xml"/><mapperresource="com/jtyhnet/mapper/UserinfoMapper.xml"/></mappers></configuration>

mapper类

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.jtyhnet.dao.UserinfoDao"><insertid="add"parameterType="userinfo">
        insert into userinfo values(#{id},#{username},#{password},#{birthday});
    </insert></mapper>

测试

@Testpublicvoidtest31()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserinfoDao userinfoDaoMapper = sqlSession.getMapper(UserinfoDao.class);Userinfo userinfo =newUserinfo();
        userinfo.setUsername("lisi");
        userinfo.setPassword("1234");
        userinfo.setBirthday(newDate());
        userinfoDaoMapper.add(userinfo);

        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述
查询数据库确认插入成功,date类型被转为varchar
在这里插入图片描述
测试查询

@Testpublicvoidtest32()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserinfoDao userinfoDaoMapper = sqlSession.getMapper(UserinfoDao.class);Userinfo userinfo = userinfoDaoMapper.findById(1);System.out.println(userinfo);
        sqlSession.close();}

在这里插入图片描述
可以发现查询结果已经由varchar转为Date类型

关于自定义转换类
packagecom.jtyhnet.typeHandler;importorg.apache.ibatis.type.BaseTypeHandler;importorg.apache.ibatis.type.JdbcType;importjava.sql.CallableStatement;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Date;publicclassMyDateTypeHandlerextendsBaseTypeHandler<Date>{@OverridepublicvoidsetNonNullParameter(PreparedStatement preparedStatement,int i,Date date,JdbcType jdbcType)throwsSQLException{
        preparedStatement.setString(i,date.getTime()+"");}@OverridepublicDategetNullableResult(ResultSet resultSet,String s)throwsSQLException{returnnewDate(resultSet.getLong(s));}@OverridepublicDategetNullableResult(ResultSet resultSet,int i)throwsSQLException{returnnewDate(resultSet.getLong(i));}@OverridepublicDategetNullableResult(CallableStatement callableStatement,int i)throwsSQLException{return callableStatement.getDate(i);}}
  1. 自定义转换类继承BaseTypeHandler<T>,其中T是javaType,上述案例中,birthday字段在java中为Date类型,在数据库中为varchar类型,因此继承BaseTypeHandler<Date>
  2. 继承后需复写4个方法 setNonNullParameter,用于preparedStatement执行sql时,对参数进行设置,i为参数角标,即第几个参数,上述案例中,java端设置的birthday为Date类型,在执行数据库insert操作时,需转为String类型才能插入到数据库Varchar类型字段中,因此,preparedStatement.setString(i,date.getTime()+""); getNullableResult(ResultSet resultSet, String s),getNullableResult(ResultSet resultSet, int i),用于将从数据库查询的结果封装为javaBean,即将查询出的String类型转为Date类型,其中s为字段名,i为字段角标。 getNullableResult(CallableStatement callableStatement, int i)为存储过程使用,i为字段角标。

plugins标签

MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据
开发步骤:
① 导入通用PageHelper的坐标
② 在mybatis核心配置文件中配置PageHelper插件
③ 测试分页数据获取

<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>3.7.5</version></dependency><dependency><groupId>com.github.jsqlparser</groupId><artifactId>jsqlparser</artifactId><version>0.9.1</version></dependency>

核心配置文件中配置分页插件

<plugins><plugininterceptor="com.github.pagehelper.PageHelper"><!--指定方言--><propertyname="dialect"value="mysql"/></plugin></plugins>

新建查询所有接口方法

List<Userinfo>findAll();

配置mapper

<selectid="findAll"resultType="userinfo">
        select * from userinfo
    </select>

测试

@Testpublicvoidtest33()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserinfoDao userinfoDaoMapper = sqlSession.getMapper(UserinfoDao.class);PageHelper.startPage(1,2);List<Userinfo> userinfoList = userinfoDaoMapper.findAll();System.out.println("userinfoList-------"+userinfoList);for(Userinfo userinfo : userinfoList){System.out.println(userinfo);}System.out.println("==================================");PageInfo<Userinfo> userinfoPageInfo =newPageInfo<>(userinfoList);System.out.println("总条数:"+userinfoPageInfo.getTotal());System.out.println("总页数:"+userinfoPageInfo.getPages());System.out.println("当前页:"+userinfoPageInfo.getPageNum());System.out.println("每页显示长度:"+userinfoPageInfo.getPageSize());System.out.println("是否第一页:"+userinfoPageInfo.isIsFirstPage());System.out.println("是否最后一页:"+userinfoPageInfo.isIsLastPage());}

在这里插入图片描述

MyBatis的多表操作

Mybatis多表查询

一对一查询

案例:
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户

createtable orderlist (
id INTNOTNULLauto_increment,
ordertime VARCHAR(255),
totalmoney decimal(20,2),
uid int,PRIMARYKEY( id ))insertinto orderlist values(null,'2021-12-30 21:46:30',5000,1);insertinto orderlist values(null,'2021-12-29 21:46:30',400,1);insertinto orderlist values(null,'2021-12-28 21:46:30',40,2);insertinto orderlist values(null,'2021-12-27 21:46:30',2321,2);insertinto orderlist values(null,'2021-12-26 21:46:30',4211,3);insertinto orderlist values(null,'2021-12-25 21:46:30',2000,4);CREATETABLE userinfo (
id INTNOTNULLauto_increment,     
username VARCHAR(50),    
password VARCHAR(50),        
birthday VARCHAR(50),PRIMARYKEY( id ));insertinto userinfo values(null,'zhangsan','123','1640784746140');insertinto userinfo values(null,'lisi','1234','1640785271387');insertinto userinfo values(null,'wangwu','123','1640784746140');insertinto userinfo values(null,'zhaoliu','123','1640784746140');

在这里插入图片描述
在这里插入图片描述
对应的sql语句:select * from orderlist o,userinfo u where o.uid=u.id;

在这里插入图片描述
IDEA中创建实体类

packagecom.jtyhnet.domain;importjava.util.Date;publicclassOrder{privateint id;privateDate ordertime;privatedouble totalmoney;//代表当前订单属于哪个客户privateOrderUserinfo orderUserinfo;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicDategetOrdertime(){return ordertime;}publicvoidsetOrdertime(Date ordertime){this.ordertime = ordertime;}publicdoublegetTotalmoney(){return totalmoney;}publicvoidsetTotalmoney(double totalmoney){this.totalmoney = totalmoney;}publicOrderUserinfogetOrderUserinfo(){return orderUserinfo;}publicvoidsetOrderUserinfo(OrderUserinfo orderUserinfo){this.orderUserinfo = orderUserinfo;}@OverridepublicStringtoString(){return"Order{"+"id="+ id +", ordertime="+ ordertime +", totalmoney="+ totalmoney +", orderUserinfo="+ orderUserinfo +'}';}}
packagecom.jtyhnet.domain;publicclassOrderUserinfo{privateint id;privateString username;privateString password;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}@OverridepublicStringtoString(){return"OrderUserinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+'}';}}

创建接口类

packagecom.jtyhnet.mapper;importcom.jtyhnet.domain.Order;importjava.util.List;publicinterfaceOrderMapper{List<Order>findAll();}

mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="jdbc.properties"/><typeAliases><typeAliastype="com.jtyhnet.domain.OrderUserinfo"alias="orderUserinfo"/><typeAliastype="com.jtyhnet.domain.Order"alias="order"/></typeAliases><environmentsdefault="mysql"><environmentid="mysql"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><mappers><mapperresource="com/jtyhnet/mapper/orderUserinfoMapper.xml"/><mapperresource="com/jtyhnet/mapper/orderMapper.xml"/></mappers></configuration>

配置mapper

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.jtyhnet.mapper.OrderMapper"><resultMapid="orderMap1"type="order"><idcolumn="id"property="id"/><resultcolumn="ordertime"property="ordertime"/><resultcolumn="totalmoney"property="totalmoney"/><resultcolumn="uid"property="orderUserinfo.id"/><resultcolumn="username"property="orderUserinfo.username"/><resultcolumn="password"property="orderUserinfo.password"/></resultMap><resultMapid="orderMap2"type="order"><resultproperty="id"column="id"/><resultproperty="ordertime"column="ordertime"/><resultproperty="totalmoney"column="totalmoney"/><associationproperty="orderUserinfo"javaType="com.jtyhnet.domain.OrderUserinfo"><resultcolumn="uid"property="id"/><resultcolumn="username"property="username"/><resultcolumn="password"property="password"/></association></resultMap><selectid="findAll"resultMap="orderMap1">
        select * from orderlist T1,userinfo T2 where T1.uid = T2.id
    </select></mapper>

由于关联后的结果,映射到order类中,字段orderUserinfo引用了另一个类OrderUserinfo,因此不能直接将结果封装,需定义resultMap,设置java类中的属性与数据库表字段相关联。设置方式有两种,一种是column为数据库中字段,property采用类名.属性,另一种是使用association 标签,单独定义引用类。

测试

@Testpublicvoidtest11()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);List<Order> orderList = orderMapper.findAll();for(Order order : orderList){System.out.println(order);}

        sqlSession.close();}

在这里插入图片描述

一对多查询

案例:
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单

改造用户OrderUserinfo类,添加订单属性

packagecom.jtyhnet.domain;importjava.util.List;publicclassOrderUserinfo{privateint id;privateString username;privateString password;//当前用户下的所有订单privateList<Order> orderList;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicList<Order>getOrderList(){return orderList;}publicvoidsetOrderList(List<Order> orderList){this.orderList = orderList;}@OverridepublicStringtoString(){return"OrderUserinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", orderList="+ orderList +'}';}}

编写接口类

packagecom.jtyhnet.mapper;importcom.jtyhnet.domain.OrderUserinfo;importjava.util.List;publicinterfaceOrderUserinfoMapper{List<OrderUserinfo>findAll();}

编写mapper配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.jtyhnet.mapper.OrderUserinfoMapper"><resultMapid="orderUserinfoResultMap1"type="com.jtyhnet.domain.OrderUserinfo"><idcolumn="id"property="id"/><resultcolumn="username"property="username"/><resultcolumn="password"property="password"/><collectionproperty="orderList"ofType="com.jtyhnet.domain.Order"><resultcolumn="oid"property="id"/><resultcolumn="ordertime"property="ordertime"/><resultcolumn="totalmoney"property="totalmoney"/></collection></resultMap><selectid="findAll"resultMap="orderUserinfoResultMap1">
        select *,o.id oid from userinfo u left join orderlist o on o.uid=u.id
    </select></mapper>

由于一个用户对应多个订单,此处订单List使用collection标签定义
测试

@Testpublicvoidtest12()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();OrderUserinfoMapper orderUserinfoMapper = sqlSession.getMapper(OrderUserinfoMapper.class);List<OrderUserinfo> orderUserinfoList = orderUserinfoMapper.findAll();for(OrderUserinfo orderUserinfo : orderUserinfoList){System.out.println(orderUserinfo.getUsername());for(Order order : orderUserinfo.getOrderList()){System.out.println(order);}System.out.println("--------------------------");}
        sqlSession.close();}

在这里插入图片描述

多对多查询

案例:
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色

用户表增加属性角色列表

packagecom.jtyhnet.domain;importjava.util.List;publicclassOrderUserinfo{privateint id;privateString username;privateString password;//当前用户下的所有订单privateList<Order> orderList;//当前用户所具有的角色privateList<Role> roleList;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicList<Order>getOrderList(){return orderList;}publicvoidsetOrderList(List<Order> orderList){this.orderList = orderList;}publicList<Role>getRoleList(){return roleList;}publicvoidsetRoleList(List<Role> roleList){this.roleList = roleList;}@OverridepublicStringtoString(){return"OrderUserinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", orderList="+ orderList +", roleList="+ roleList +'}';}}

接口类增加方法

List<OrderUserinfo>findAllUserAndRole();

设置mapper

<resultMapid="orderMap2"type="order"><resultproperty="id"column="id"/><resultproperty="ordertime"column="ordertime"/><resultproperty="totalmoney"column="totalmoney"/><associationproperty="orderUserinfo"javaType="com.jtyhnet.domain.OrderUserinfo"><resultcolumn="uid"property="id"/><resultcolumn="username"property="username"/><resultcolumn="password"property="password"/></association></resultMap><selectid="findAll"resultMap="orderMap1">
        select * from orderlist T1,userinfo T2 where T1.uid = T2.id
    </select>

测试

@Testpublicvoidtest13()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();OrderUserinfoMapper orderUserinfoMapper = sqlSession.getMapper(OrderUserinfoMapper.class);List<OrderUserinfo> allUserAndRole = orderUserinfoMapper.findAllUserAndRole();for(OrderUserinfo orderUserinfo : allUserAndRole){System.out.println(orderUserinfo.getUsername());for(Role role : orderUserinfo.getRoleList()){System.out.println(role);}System.out.println("---------------");}
        sqlSession.close();}

在这里插入图片描述
总结:
MyBatis多表配置方式:
一对一配置:使用<resultMap>做配置
一对多配置:使用<resultMap>+<collection>做配置
多对多配置:使用<resultMap>+<collection>做配置

MyBatis注解开发

MyBatis的常用注解

这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了。我们先围绕一些基本的CRUD来学习,再学习复杂映射多表操作。
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@One:实现一对一结果集封装
@Many:实现一对多结果集封装

MyBatis的增删改查

@Insert插入数据

测试注解开发向数据库表中insert数据

实体类

packagecom.jtyhnet.domain;importjava.util.Date;publicclassUserinfo{privateint id;privateString username;privateString password;privateDate birthday;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicDategetBirthday(){return birthday;}publicvoidsetBirthday(Date birthday){this.birthday = birthday;}@OverridepublicStringtoString(){return"Userinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", birthday="+ birthday +'}';}}

接口类

packagecom.jtyhnet.mapper;importcom.jtyhnet.domain.Userinfo;importorg.apache.ibatis.annotations.Insert;publicinterfaceUserinfoMapper{@Insert("insert into userinfo values (#{id},#{username},#{password},#{birthday})")voidadd(Userinfo userinfo);}

自定义转换器

packagecom.jtyhnet.typeHandler;importorg.apache.ibatis.type.BaseTypeHandler;importorg.apache.ibatis.type.JdbcType;importjava.sql.CallableStatement;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Date;publicclassMyDateTypeHandler3extendsBaseTypeHandler<Date>{@OverridepublicvoidsetNonNullParameter(PreparedStatement preparedStatement,int i,Date date,JdbcType jdbcType)throwsSQLException{
        preparedStatement.setString(i,date.getTime()+"");}@OverridepublicDategetNullableResult(ResultSet resultSet,String s)throwsSQLException{returnnewDate(resultSet.getLong(s));}@OverridepublicDategetNullableResult(ResultSet resultSet,int i)throwsSQLException{returnnewDate(resultSet.getLong(i));}@OverridepublicDategetNullableResult(CallableStatement callableStatement,int i)throwsSQLException{return callableStatement.getDate(i);}}

核心配置类

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="jdbc.properties"/><typeHandlers><typeHandlerhandler="com.jtyhnet.typeHandler.MyDateTypeHandler3"/></typeHandlers><environmentsdefault="mysql"><environmentid="mysql"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><mappers><!--扫描使用注解的类--><mapperclass="com.jtyhnet.mapper.UserinfoMapper"/><!--扫描使用注解的类所在的包--><!--        <package name="com.jtyhnet.mapper"/>--></mappers></configuration>

使用注解开发后,<mappers>标签内使用<mapper class>扫描使用注解的类或<package>扫描使用注解的类所在的包

测试

importcom.jtyhnet.domain.Userinfo;importcom.jtyhnet.mapper.UserinfoMapper;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Before;importorg.junit.Test;importjava.io.IOException;importjava.io.InputStream;importjava.util.Date;publicclass test1 {privateUserinfoMapper userinfoMapper;privateSqlSession sqlSession;@Beforepublicvoidbefore()throwsIOException{InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory =newSqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession = sqlSessionFactory.openSession();
        userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);}@TestpublicvoidtestAdd(){Userinfo userinfo =newUserinfo();
        userinfo.setUsername("张三");
        userinfo.setPassword("1234");
        userinfo.setBirthday(newDate());
        userinfoMapper.add(userinfo);
        sqlSession.commit();
        sqlSession.close();}}

在这里插入图片描述

@Delete删除数据

接口类中增加

@Delete("delete from userinfo where id = #{id}")voiddelete(int id);

测试

@TestpublicvoidtestDelete(){
        userinfoMapper.delete(8);
        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述

@Update更新数据

@Update("update userinfo set username=#{username},password=#{password},birthday=#{birthday} where id = #{id}")voidupdate(Userinfo userinfo);
@TestpublicvoidtestUpdate(){Userinfo userinfo =newUserinfo();
        userinfo.setId(7);
        userinfo.setUsername("李四1");
        userinfo.setPassword("wer111");
        userinfo.setBirthday(newDate());
        userinfoMapper.update(userinfo);}

在这里插入图片描述

@Select查询数据

@Select("select * from userinfo")List<Userinfo>findAll();@Select("select * from userinfo where id = #{id}")UserinfofindById(int id);
@TestpublicvoidtestFindAll(){List<Userinfo> userinfoList = userinfoMapper.findAll();for(Userinfo userinfo : userinfoList){System.out.println(userinfo);}}@TestpublicvoidtestFindById(){Userinfo userinfo = userinfoMapper.findById(1);System.out.println(userinfo);}

在这里插入图片描述

在这里插入图片描述

复杂映射

实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解,@Result注解,@One注解,@Many注解组合完成复杂关系的配置
注解说明@Results代替的是标签<resultMap>该注解中可以使用单个@Result注解,也可以使用@Result集合。使用格式:@Results({@Result(),@Result()})或@Results(@Result())@Result代替了<id>标签和<result>标签
@Result中属性介绍:
column:数据库的列名
property:需要装配的属性名
one:需要使用的@One 注解(@Result([email protected])()))
many:需要使用的@Many 注解(@Result([email protected])()))@One(一对一)代替了<assocation> 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One注解属性介绍:select: 指定用来多表查询的 sqlmapper
使用格式:@Result(column=" “,property=”",[email protected](select=""))@Many(多对一)代替了<collection>标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。
使用格式:@Result(property="",column="",[email protected](select=""))

一对一查询

订单与客户案例
实体类

packagecom.jtyhnet.domain;publicclassOrder{privateint id;privateDouble totalMoney;privateUserinfo userinfo;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicDoublegetTotalMoney(){return totalMoney;}publicvoidsetTotalMoney(Double totalMoney){this.totalMoney = totalMoney;}publicUserinfogetUserinfo(){return userinfo;}publicvoidsetUserinfo(Userinfo userinfo){this.userinfo = userinfo;}@OverridepublicStringtoString(){return"Order{"+"id="+ id +", totalMoney="+ totalMoney +", userinfo="+ userinfo +'}';}}

接口类

packagecom.jtyhnet.mapper;importcom.jtyhnet.domain.Order;importcom.jtyhnet.domain.Userinfo;importorg.apache.ibatis.annotations.One;importorg.apache.ibatis.annotations.Result;importorg.apache.ibatis.annotations.Results;importorg.apache.ibatis.annotations.Select;importjava.util.List;publicinterfaceOrderMapper{@Select("select * from orderlist")@Results({@Result(id =true,property ="id",column ="id"),@Result(property ="totalMoney",column ="totalmoney"),@Result(property ="userinfo",column ="uid",javaType =Userinfo.class,
                    one [email protected](select ="com.jtyhnet.mapper.UserinfoMapper.findById"))})List<Order>findAll();}

测试

@TestpublicvoidtestFindAllOrder(){List<Order> orderList = orderMapper.findAll();for(Order order : orderList){System.out.println(order);}}

在这里插入图片描述
一对一查询,使用注解开发,由于结果中有引用对象,使用@Results定义结果集,@Result定义每一个字段,

@Result(property ="userinfo",column ="uid",javaType =Userinfo.class,
                    one [email protected](select ="com.jtyhnet.mapper.UserinfoMapper.findById"))

引用类的结果,property 为java类中属性名称,column 为主体类关联引用类,即数据库中主表关联附表使用的关联字段,javaType 定义该属性的类型,one用来定义根据该关联字段查询该条数据。

一对多查询

用户下有多个订单

packagecom.jtyhnet.domain;importjava.util.Date;importjava.util.List;publicclassUserinfo{privateint id;privateString username;privateString password;privateDate birthday;//用户下所有订单privateList<Order> orderList;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicDategetBirthday(){return birthday;}publicvoidsetBirthday(Date birthday){this.birthday = birthday;}publicList<Order>getOrderList(){return orderList;}publicvoidsetOrderList(List<Order> orderList){this.orderList = orderList;}@OverridepublicStringtoString(){return"Userinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", birthday="+ birthday +", orderList="+ orderList +'}';}}
@Select("select * from userinfo")@Results({@Result(id =true,property ="id",column ="id"),@Result(property ="username",column ="username"),@Result(property ="password",column ="password"),@Result(property ="birthday",column ="birthday"),@Result(property ="orderList",column ="id",javaType =List.class,
                    many [email protected](select ="com.jtyhnet.mapper.OrderMapper.findByUid"))})List<Userinfo>findAllUserAndOrder();
@Select("select * from orderlist where uid = #{uid}")List<Order>findByUid(int uid);
@TestpublicvoidfindAllUserAndOrder(){List<Userinfo> allUserAndOrder = userinfoMapper.findAllUserAndOrder();for(Userinfo userinfo : allUserAndOrder){System.out.println(userinfo.getUsername());for(Order order : userinfo.getOrderList()){System.out.println(order);}}}

在这里插入图片描述
一对多查询时,与一对一查询基本类似,只是将引用类javaType改为List.class,使用many查询附表

#####多对多查询

用户与角色关联案例

角色类

packagecom.jtyhnet.domain;publicclassRole{privateint id;privateString roleName;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetRoleName(){return roleName;}publicvoidsetRoleName(String roleName){this.roleName = roleName;}@OverridepublicStringtoString(){return"Role{"+"id="+ id +", roleName='"+ roleName +'\''+'}';}}

用户类

packagecom.jtyhnet.domain;importjava.util.Date;importjava.util.List;publicclassUserinfo{privateint id;privateString username;privateString password;privateDate birthday;//用户下所有订单privateList<Order> orderList;privateList<Role> roleList;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicDategetBirthday(){return birthday;}publicvoidsetBirthday(Date birthday){this.birthday = birthday;}publicList<Order>getOrderList(){return orderList;}publicvoidsetOrderList(List<Order> orderList){this.orderList = orderList;}publicList<Role>getRoleList(){return roleList;}publicvoidsetRoleList(List<Role> roleList){this.roleList = roleList;}@OverridepublicStringtoString(){return"Userinfo{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", birthday="+ birthday +", orderList="+ orderList +", roleList="+ roleList +'}';}}
@Select("select * from userinfo")@Results({@Result(id =true,property ="id",column ="id"),@Result(property ="username",column ="username"),@Result(property ="password",column ="password"),@Result(property ="birthday",column ="birthday"),@Result(property ="roleList",column ="id",javaType =List.class,
                    many [email protected](select ="com.jtyhnet.mapper.RoleMapper.findRoleByUid"))})List<Userinfo>findAllUserAndRole();
@Select("select T1.* from role T1 inner join user_role T2 on T1.id = T2.role_id where T2.user_id = #{uid}")List<Role>findRoleByUid(int uid);

测试

@TestpublicvoidfindAllUserAndRole(){List<Userinfo> allUserAndRole = userinfoMapper.findAllUserAndRole();for(Userinfo userinfo : allUserAndRole){System.out.println(userinfo.getUsername());for(Role role : userinfo.getRoleList()){System.out.println(role);}System.out.println("+++++++++++++++++++++");}}

在这里插入图片描述


本文转载自: https://blog.csdn.net/zwk_sys/article/details/122212754
版权归原作者 寻找你的海洋 所有, 如有侵权,请联系我们删除。

“Mybatis框架知识整理”的评论:

还没有评论