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>
测试查询数据 测试用表
数据库表映射类
package com.jtyhnet.domain;
public class Account {
private int id;
private String name;
private float money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
测试代码
import com.jtyhnet.domain.Account;
import org.junit.Test;
import java.sql.*;
public class JDBCTest1 {
@Test
public void test1() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///test", "root", "root");
PreparedStatement preparedStatement = connection.prepareStatement("select * from account");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Account account = new Account();
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();
}
}
插入数据
@Test
public void test2() throws ClassNotFoundException, SQLException {
Account account = new Account();
account.setName("wangwu");
account.setMoney(6000);
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///test", "root", "root");
PreparedStatement 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
创建测试用表
创建实体类
package com.jtyhnet.domain;
public class User {
private int id;
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
编写映射文件UserMapper.xml
<?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="userMapper">
<select id="findAll" resultType="com.jtyhnet.domain.User">
select * from USER
</select>
</mapper>
编写mybatis核心配置文件SqlMapConfig.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jtyhnet/mapper/UserMapper.xml"/>
</mappers>
</configuration>
进行测试
import com.jtyhnet.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest1 {
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("userMapper.findAll");
System.out.println(userList);
sqlSession.close();
}
}
MyBatis的映射文件概述
MyBatis的增删改查操作
MyBatis的插入数据操作
UserMapper.xml中添加
<insert id="add" parameterType="com.jtyhnet.domain.User">
insert into user values (#{id},#{username},#{password})
</insert>
测试代码
@Test
public void test2() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setPassword("12233");
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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中添加
<update id="update" parameterType="com.jtyhnet.domain.User">
update user set username=#{username},password=#{password} where id = #{id}
</update>
@Test
public void test3() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
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的删除数据操作
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
@Test
public void test4() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.jtyhnet.domain.User">
select * from USER
</select>
<insert id="add" parameterType="com.jtyhnet.domain.User">
insert into user values (#{id},#{username},#{password})
</insert>
<update id="update" parameterType="com.jtyhnet.domain.User">
update user set username=#{username},password=#{password} where id = #{id}
</update>
<delete id="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 类型设置一个短的名字。原来的类型名称配置如下
<select id="findAll" resultType="com.jtyhnet.domain.User">
select * from USER
</select>
配置typeAliases,为com.jtyhnet.domain.User定义别名为user
<?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="jdbc.properties"/>
<typeAliases>
<typeAlias type="com.jtyhnet.domain.User" alias="user"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jtyhnet/mapper/UserMapper.xml"/>
</mappers>
</configuration>
使用别名配置mapper
<?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="userMapper">
<select id="findAll" resultType="user">
select * from USER
</select>
<insert id="add" parameterType="com.jtyhnet.domain.User">
insert into user values (#{id},#{username},#{password})
</insert>
<update id="update" parameterType="com.jtyhnet.domain.User">
update user set username=#{username},password=#{password} where id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
</mapper>
执行查询测试 上面我们是自定义的别名,mybatis框架已经为我们设置好的一些常用的类型的别名
别名 | 数据类型 |
---|
string | String | long | Long | int | Integer | double | Double | boolean | Boolean | … … | … … |
知识小结
核心配置文件常用配置: 1、properties标签:该标签可以加载外部的properties文件
<properties resource="jdbc.properties"/>
2、typeAliases标签:设置类型别名
<typeAliases>
<typeAlias type="com.jtyhnet.domain.User" alias="user"/>
</typeAliases>
3、mappers标签:加载映射配置
<mappers>
<mapper resource="com/jtyhnet/mapper/UserMapper.xml"/>
</mappers>
4、environments标签:数据源环境配置标签
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
MyBatis相应API
SqlSession工厂构建器SqlSessionFactoryBuilder
常用API:SqlSessionFactory build(InputStream inputStream) 通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
其中, Resources 工具类,这个类在 org.apache.ibatis.io 包中。Resources 类帮助你从类路径下、文件系统或一个 web URL 中加载资源文件。
SqlSession工厂对象SqlSessionFactory
SqlSessionFactory 有多个个方法创建 SqlSession 实例。常用的有如下两个:
方法 | 解释 |
---|
openSession() | 会默认开启一个事务,但事务不会自动提交,也就意味着需要手动提交该事务,更新操作数据才会持久化到数据库中 | openSession(boolean autoCommit) | 参数为是否自动提交,如果设置为true,那么不需要手动提交事务 |
SqlSession会话对象
SqlSession 实例在 MyBatis 中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。 执行语句的方法主要有:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
操作事务的方法主要有:
void commit()
void rollback()
MyBatis的Dao层实现方式
传统开发方式
package com.jtyhnet.dao;
import com.jtyhnet.domain.User;
import java.util.List;
public interface UserDao {
List<User> findAll() throws Exception;
}
package com.jtyhnet.dao.impl;
import com.jtyhnet.dao.UserDao;
import com.jtyhnet.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class UserDaoImpl implements UserDao {
@Override
public List<User> findAll() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("userMapper.findAll");
return userList;
}
}
测试
@Test
public void test5() throws Exception {
UserDao userDao = new UserDaoImpl();
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的类型相同
接口类
package com.jtyhnet.dao;
import com.jtyhnet.domain.User;
import java.io.IOException;
import java.util.List;
public interface UserDao {
List<User> findAll() throws IOException;
User findById(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.jtyhnet.dao.UserDao">
<select id="findAll" resultType="user">
select * from user
</select>
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
@Test
public void test21() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
接口类
package com.jtyhnet.dao;
import com.jtyhnet.domain.User;
import java.io.IOException;
import java.util.List;
public interface UserDao {
List<User> findAll() throws IOException;
User findById(int id);
User findByCondition(User user);
}
mapper配置
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=0">
and id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
</where>
</select>
测试代码
@Test
public void test22() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setId(1);
user.setUsername("zhangsan");
User user1 = userDaoMapper.findByCondition(user);
System.out.println(user1);
}
改变条件再次测试
@Test
public void test22() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setId(1);
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增加
<select id="findByIds" parameterType="list" resultType="user">
select * from user
<where>
<foreach collection="list" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
@Test
public void test23() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);
ArrayList<Integer> idList = new ArrayList<>();
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 重用的目的
<sql id="selectAllUser">select * from user</sql>
<include refid="selectAllUser"/>
<?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.jtyhnet.dao.UserDao">
<sql id="selectAllUser">select * from user</sql>
<select id="findAll" resultType="user">
<include refid="selectAllUser"/>
</select>
<select id="findById" parameterType="int" resultType="user">
<include refid="selectAllUser"/> where id = #{id}
</select>
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectAllUser"/>
<where>
<if test="id!=0">
and id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
</where>
</select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectAllUser"/>
<where>
<foreach collection="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核心配置文件中进行注册 ④ 测试转换是否正确
创建测试用表
CREATE TABLE userinfo (
id INT NOT NULL auto_increment,
username VARCHAR ( 50 ) ,
password VARCHAR ( 50 ) ,
birthday VARCHAR ( 50 ) ,
PRIMARY KEY ( id )
);
insert into userinfo values (null,'zhangsan','123','1640784746140');
创建实体类
package com.jtyhnet.domain;
import java.util.Date;
public class Userinfo {
private int id;
private String username;
private String password;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Userinfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
插入数据接口方法
package com.jtyhnet.dao;
import com.jtyhnet.domain.Userinfo;
public interface UserinfoDao {
void add(Userinfo userinfo);
}
定义转换类
package com.jtyhnet.typeHandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class MyDateTypeHandler extends BaseTypeHandler<Date> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i,date.getTime()+"");
}
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}
mybatis核心配置类 添加userinfo别名,<typeHandlers>注册自定义转换类
<?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="jdbc.properties"/>
<typeAliases>
<typeAlias type="com.jtyhnet.domain.User" alias="user"/>
<typeAlias type="com.jtyhnet.domain.Userinfo" alias="userinfo"/>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.jtyhnet.typeHandler.MyDateTypeHandler"/>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jtyhnet/mapper/UserDaoMapper.xml"/>
<mapper resource="com/jtyhnet/mapper/UserinfoMapper.xml"/>
</mappers>
</configuration>
mapper类
<?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.jtyhnet.dao.UserinfoDao">
<insert id="add" parameterType="userinfo">
insert into userinfo values(#{id},#{username},#{password},#{birthday});
</insert>
</mapper>
测试
@Test
public void test31() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserinfoDao userinfoDaoMapper = sqlSession.getMapper(UserinfoDao.class);
Userinfo userinfo = new Userinfo();
userinfo.setUsername("lisi");
userinfo.setPassword("1234");
userinfo.setBirthday(new Date());
userinfoDaoMapper.add(userinfo);
sqlSession.commit();
sqlSession.close();
}
查询数据库确认插入成功,date类型被转为varchar 测试查询
@Test
public void test32() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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类型
关于自定义转换类
package com.jtyhnet.typeHandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class MyDateTypeHandler extends BaseTypeHandler<Date> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i,date.getTime()+"");
}
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}
- 自定义转换类继承BaseTypeHandler<T>,其中T是javaType,上述案例中,birthday字段在java中为Date类型,在数据库中为varchar类型,因此继承BaseTypeHandler<Date>
- 继承后需复写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>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
新建查询所有接口方法
List<Userinfo> findAll();
配置mapper
<select id="findAll" resultType="userinfo">
select * from userinfo
</select>
测试
@Test
public void test33() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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 = new PageInfo<>(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多表查询
一对一查询
案例: 用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户 一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
create table orderlist (
id INT NOT NULL auto_increment,
ordertime VARCHAR ( 255 ) ,
totalmoney decimal(20,2),
uid int,
PRIMARY KEY ( id )
)
insert into orderlist values (null,'2021-12-30 21:46:30',5000,1);
insert into orderlist values (null,'2021-12-29 21:46:30',400,1);
insert into orderlist values (null,'2021-12-28 21:46:30',40,2);
insert into orderlist values (null,'2021-12-27 21:46:30',2321,2);
insert into orderlist values (null,'2021-12-26 21:46:30',4211,3);
insert into orderlist values (null,'2021-12-25 21:46:30',2000,4);
CREATE TABLE userinfo (
id INT NOT NULL auto_increment,
username VARCHAR ( 50 ) ,
password VARCHAR ( 50 ) ,
birthday VARCHAR ( 50 ) ,
PRIMARY KEY ( id )
);
insert into userinfo values (null,'zhangsan','123','1640784746140');
insert into userinfo values (null,'lisi','1234','1640785271387');
insert into userinfo values (null,'wangwu','123','1640784746140');
insert into userinfo values (null,'zhaoliu','123','1640784746140');
对应的sql语句:select * from orderlist o,userinfo u where o.uid=u.id;
IDEA中创建实体类
package com.jtyhnet.domain;
import java.util.Date;
public class Order {
private int id;
private Date ordertime;
private double totalmoney;
private OrderUserinfo orderUserinfo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getOrdertime() {
return ordertime;
}
public void setOrdertime(Date ordertime) {
this.ordertime = ordertime;
}
public double getTotalmoney() {
return totalmoney;
}
public void setTotalmoney(double totalmoney) {
this.totalmoney = totalmoney;
}
public OrderUserinfo getOrderUserinfo() {
return orderUserinfo;
}
public void setOrderUserinfo(OrderUserinfo orderUserinfo) {
this.orderUserinfo = orderUserinfo;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime=" + ordertime +
", totalmoney=" + totalmoney +
", orderUserinfo=" + orderUserinfo +
'}';
}
}
package com.jtyhnet.domain;
public class OrderUserinfo {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "OrderUserinfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
创建接口类
package com.jtyhnet.mapper;
import com.jtyhnet.domain.Order;
import java.util.List;
public interface OrderMapper {
List<Order> findAll();
}
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="jdbc.properties"/>
<typeAliases>
<typeAlias type="com.jtyhnet.domain.OrderUserinfo" alias="orderUserinfo"/>
<typeAlias type="com.jtyhnet.domain.Order" alias="order"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jtyhnet/mapper/orderUserinfoMapper.xml"/>
<mapper resource="com/jtyhnet/mapper/orderMapper.xml"/>
</mappers>
</configuration>
配置mapper
<?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.jtyhnet.mapper.OrderMapper">
<resultMap id="orderMap1" type="order">
<id column="id" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="totalmoney" property="totalmoney"/>
<result column="uid" property="orderUserinfo.id"/>
<result column="username" property="orderUserinfo.username"/>
<result column="password" property="orderUserinfo.password"/>
</resultMap>
<resultMap id="orderMap2" type="order">
<result property="id" column="id"/>
<result property="ordertime" column="ordertime"/>
<result property="totalmoney" column="totalmoney"/>
<association property="orderUserinfo" javaType="com.jtyhnet.domain.OrderUserinfo">
<result column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</association>
</resultMap>
<select id="findAll" resultMap="orderMap1">
select * from orderlist T1,userinfo T2 where T1.uid = T2.id
</select>
</mapper>
由于关联后的结果,映射到order类中,字段orderUserinfo引用了另一个类OrderUserinfo,因此不能直接将结果封装,需定义resultMap,设置java类中的属性与数据库表字段相关联。设置方式有两种,一种是column为数据库中字段,property采用类名.属性,另一种是使用association 标签,单独定义引用类。
测试
@Test
public void test11() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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类,添加订单属性
package com.jtyhnet.domain;
import java.util.List;
public class OrderUserinfo {
private int id;
private String username;
private String password;
private List<Order> orderList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
@Override
public String toString() {
return "OrderUserinfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", orderList=" + orderList +
'}';
}
}
编写接口类
package com.jtyhnet.mapper;
import com.jtyhnet.domain.OrderUserinfo;
import java.util.List;
public interface OrderUserinfoMapper {
List<OrderUserinfo> findAll();
}
编写mapper配置文件
<?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.jtyhnet.mapper.OrderUserinfoMapper">
<resultMap id="orderUserinfoResultMap1" type="com.jtyhnet.domain.OrderUserinfo">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<collection property="orderList" ofType="com.jtyhnet.domain.Order">
<result column="oid" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="totalmoney" property="totalmoney"/>
</collection>
</resultMap>
<select id="findAll" resultMap="orderUserinfoResultMap1">
select *,o.id oid from userinfo u left join orderlist o on o.uid=u.id
</select>
</mapper>
由于一个用户对应多个订单,此处订单List使用collection标签定义 测试
@Test
public void test12() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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();
}
多对多查询
案例: 用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用 多对多查询的需求:查询用户同时查询出该用户的所有角色
用户表增加属性角色列表
package com.jtyhnet.domain;
import java.util.List;
public class OrderUserinfo {
private int id;
private String username;
private String password;
private List<Order> orderList;
private List<Role> roleList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
@Override
public String toString() {
return "OrderUserinfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", orderList=" + orderList +
", roleList=" + roleList +
'}';
}
}
接口类增加方法
List<OrderUserinfo> findAllUserAndRole();
设置mapper
<resultMap id="orderMap2" type="order">
<result property="id" column="id"/>
<result property="ordertime" column="ordertime"/>
<result property="totalmoney" column="totalmoney"/>
<association property="orderUserinfo" javaType="com.jtyhnet.domain.OrderUserinfo">
<result column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</association>
</resultMap>
<select id="findAll" resultMap="orderMap1">
select * from orderlist T1,userinfo T2 where T1.uid = T2.id
</select>
测试
@Test
public void test13() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().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数据
实体类
package com.jtyhnet.domain;
import java.util.Date;
public class Userinfo {
private int id;
private String username;
private String password;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Userinfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
接口类
package com.jtyhnet.mapper;
import com.jtyhnet.domain.Userinfo;
import org.apache.ibatis.annotations.Insert;
public interface UserinfoMapper {
@Insert("insert into userinfo values (#{id},#{username},#{password},#{birthday})")
void add(Userinfo userinfo);
}
自定义转换器
package com.jtyhnet.typeHandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class MyDateTypeHandler3 extends BaseTypeHandler<Date> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i,date.getTime()+"");
}
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}
核心配置类
<?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="jdbc.properties"/>
<typeHandlers>
<typeHandler handler="com.jtyhnet.typeHandler.MyDateTypeHandler3"/>
</typeHandlers>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.jtyhnet.mapper.UserinfoMapper"/>
</mappers>
</configuration>
使用注解开发后,<mappers>标签内使用<mapper class>扫描使用注解的类或<package>扫描使用注解的类所在的包
测试
import com.jtyhnet.domain.Userinfo;
import com.jtyhnet.mapper.UserinfoMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
public class test1 {
private UserinfoMapper userinfoMapper;
private SqlSession sqlSession;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession();
userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);
}
@Test
public void testAdd() {
Userinfo userinfo = new Userinfo();
userinfo.setUsername("张三");
userinfo.setPassword("1234");
userinfo.setBirthday(new Date());
userinfoMapper.add(userinfo);
sqlSession.commit();
sqlSession.close();
}
}
@Delete删除数据
接口类中增加
@Delete("delete from userinfo where id = #{id}")
void delete(int id);
测试
@Test
public void testDelete(){
userinfoMapper.delete(8);
sqlSession.commit();
sqlSession.close();
}
@Update更新数据
@Update("update userinfo set username=#{username},password=#{password},birthday=#{birthday} where id = #{id}")
void update(Userinfo userinfo);
@Test
public void testUpdate(){
Userinfo userinfo = new Userinfo();
userinfo.setId(7);
userinfo.setUsername("李四1");
userinfo.setPassword("wer111");
userinfo.setBirthday(new Date());
userinfoMapper.update(userinfo);
}
@Select查询数据
@Select("select * from userinfo")
List<Userinfo> findAll();
@Select("select * from userinfo where id = #{id}")
Userinfo findById(int id);
@Test
public void testFindAll(){
List<Userinfo> userinfoList = userinfoMapper.findAll();
for (Userinfo userinfo : userinfoList) {
System.out.println(userinfo);
}
}
@Test
public void testFindById(){
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(one=@One)())) many:需要使用的@Many 注解(@Result(many=@many)())) | @One(一对一) | 代替了<assocation> 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One注解属性介绍:select: 指定用来多表查询的 sqlmapper 使用格式:@Result(column=" “,property=”",one=@One(select="")) | @Many(多对一) | 代替了<collection>标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。 使用格式:@Result(property="",column="",many=@Many(select="")) |
一对一查询
订单与客户案例 实体类
package com.jtyhnet.domain;
public class Order {
private int id;
private Double totalMoney;
private Userinfo userinfo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Double getTotalMoney() {
return totalMoney;
}
public void setTotalMoney(Double totalMoney) {
this.totalMoney = totalMoney;
}
public Userinfo getUserinfo() {
return userinfo;
}
public void setUserinfo(Userinfo userinfo) {
this.userinfo = userinfo;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", totalMoney=" + totalMoney +
", userinfo=" + userinfo +
'}';
}
}
接口类
package com.jtyhnet.mapper;
import com.jtyhnet.domain.Order;
import com.jtyhnet.domain.Userinfo;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@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 = @One(select = "com.jtyhnet.mapper.UserinfoMapper.findById"))
})
List<Order> findAll();
}
测试
@Test
public void testFindAllOrder(){
List<Order> orderList = orderMapper.findAll();
for (Order order : orderList) {
System.out.println(order);
}
}
一对一查询,使用注解开发,由于结果中有引用对象,使用@Results定义结果集,@Result定义每一个字段,
@Result(property = "userinfo",column = "uid",javaType = Userinfo.class,
one = @One(select = "com.jtyhnet.mapper.UserinfoMapper.findById"))
引用类的结果,property 为java类中属性名称,column 为主体类关联引用类,即数据库中主表关联附表使用的关联字段,javaType 定义该属性的类型,one用来定义根据该关联字段查询该条数据。
一对多查询
用户下有多个订单
package com.jtyhnet.domain;
import java.util.Date;
import java.util.List;
public class Userinfo {
private int id;
private String username;
private String password;
private Date birthday;
private List<Order> orderList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
@Override
public String toString() {
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 = @Many(select = "com.jtyhnet.mapper.OrderMapper.findByUid"))
})
List<Userinfo> findAllUserAndOrder();
@Select("select * from orderlist where uid = #{uid}")
List<Order> findByUid(int uid);
@Test
public void findAllUserAndOrder(){
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查询附表
#####多对多查询
用户与角色关联案例
角色类
package com.jtyhnet.domain;
public class Role {
private int id;
private String roleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
'}';
}
}
用户类
package com.jtyhnet.domain;
import java.util.Date;
import java.util.List;
public class Userinfo {
private int id;
private String username;
private String password;
private Date birthday;
private List<Order> orderList;
private List<Role> roleList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
@Override
public String toString() {
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 = @Many(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);
测试
@Test
public void findAllUserAndRole(){
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("+++++++++++++++++++++");
}
}
|