Mybatis学习流程

本文详细介绍了Mybatis框架,从原始jdbc操作的问题出发,阐述了解决这些问题的Mybatis框架。内容涵盖Mybatis的简介、快速入门、映射文件、核心配置文件、API、Dao层实现、动态SQL及SQL片段抽取、多表查询等方面,旨在帮助读者全面理解并掌握Mybatis的使用。
摘要由CSDN通过智能技术生成

Mybatis简介


1. 原始jdbc操作

Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://数据库路径", "用户名", "密码");
PreparedStatement statement = connection.prepareStatement("sql语句");
// 查询
ResultSet rs = statement.executeQuert();
// 增删改
statement.executeUpdate();
statement.close():
connection.close();

2. 原始jdbc操作问题

  1. 数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能
  2. sql 语句在代码中硬编码,造成代码不易维护,实际应用 sql 变化的可能较大,sql 变动需要改变java代码。
  3. 查询操作时,需要手动将结果集中的数据手动封装到实体中。插入操作时,需要手动将实体的数据设置到sql语句的占位符位置

3. 解决方法

  1. 使用数据库连接池初始化连接资源
  2. 将sql语句抽取到xml配置文件中
  3. 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射

4. 什么是Mybatis

mybatis 是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。

mybatis通过xml或注解的方式将要执行的各种 statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。

最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc 进行了封装,屏蔽了jdbc api 底层访问细节,使我们不用与jdbc api 打交道,就可以完成对数据库的持久化操作。

5. Mybatis快速入门

1. 开发步骤

  1. 添加MyBatis的坐标
  2. 创建数据表
  3. 编写实体类
  4. 编写映射文件UserMapper.xml
  5. 编写核心文件SqlMapConfig.xml
  6. 编写测试类

2. 代码实现

  1. 导入坐标
<!--mybatis坐标-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>    
    <groupId>mysql</groupId>   
    <artifactId>mysql-connector-java</artifactId>    
    <version>5.1.6</version>    
    <scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>    
    <groupId>junit</groupId>    
    <artifactId>junit</artifactId>    
    <version>4.12</version>    
    <scope>test</scope>
</dependency>
<!--日志坐标-->
<dependency>    
    <groupId>log4j</groupId>    
    <artifactId>log4j</artifactId>    
    <version>1.2.12</version>
</dependency>
  1. 创建数据表
属性名类型其它
idint
usernamevarchar
passwordvarchar
  1. 编写实体类
public class User {    
	private int id;    
	private String username;    
	private String password;
    // 生成setter和getter方法和toString
}
  1. 编写UserMapper映射文件
<?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">
<!-- 上面的头是固定的,直接cv上 -->

<mapper namespace="userMapper">
	<select id="findAll" resultType="com.jerry.domain.User">        
		select * from User    
	</select>
</mapper>
  1. 编写MyBatis核心文件sqlMapConfig.xml
<!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"/>            
			<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/jerry/mapper/UserMapper.xml"/> 
	</mappers>
</configuration>
  1. 测试
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
List<User> userList = sqlSession.selectList("userMapper.findAll");
//打印结果
System.out.println(userList);
//释放资源
sqlSession.close();

Mybatis映射文件


1. 文件属性介绍

<?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为命名空间,和语句的id组成查询标识 -->
<mapper namespace="userMapper">
	<!-- 查询操作select,还有insert,update,delete标签 -->
	<!-- resultType查询结果对应的实体类型 | id与namespace组成标识 -->
	<select id="findAll" resultType="com.jerry.domain.User">        
		<!-- sql语句 -->
		select * from User    
	</select>
</mapper>

2. Mybatis的增删改查操作

1. Mybatis的插入数据操作

<!-- UserMapper映射文件 -->
<mapper namespace="userMapper">    
	<insert id="add" parameterType="com.jerry.domain.User">        
		insert into user values(#{id},#{username},#{password})    
	</insert>
</mapper>
// 测试
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(insert);
//提交事务
sqlSession.commit();
sqlSession.close();
  1. 使用insert标签
  2. parameterType指定插入的数据类型
  3. sql使用#{}的方法引用实体属性值
  4. 插入使用API => sqlSession.insert(“命名空间.id”, 实体对象);
  5. 插入数据涉及到了数据变化,Mybatis需要手动提交事务 => sqlSession.commit();

2. Mybatis的修改数据操作

<mapper namespace="userMapper">
    <update id="update" parameterType="com.jerry.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>
</mapper>

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int update = sqlSession.update("userMapper.update", user);
System.out.println(update);
sqlSession.commit();
sqlSession.close();

3. Mybatis的删除数据操作

<mapper namespace="userMapper">
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
</mapper>
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();

如果引入的是单个参数,#{}里面可以写任意字符串引用这个参数,但保证可读性


Mybatis核心配置文件


1. Mybatis核心配置文件层级关系

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

2. Mybatis常用配置解析

1. environments标签

数据库环境的配置,支持多环境配置

<environments default="development">  <!-- default默认环境名称 -->      
	<environment id="development">  <!-- 指定当前环境名称 -->
		<transactionManager type="JDBC"/>  <!-- 事务管理类型指定为JDBC -->
		<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>

事务管理器的类型:

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

数据源的类型:

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

2. mapper标签

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

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

3. properties标签

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

<!-- 引入,通过${key}使用 -->
<properties resource="jdbc.properties"></properties>

4. typeAliases标签

类型别名是为Java 类型设置一个短的名字

<!-- 原始写法 -->
								<!-- 全限定名 -->
<select id="findAll" resultType="com.jerry.domain.User">
	select * from User
</select>
<!-- 别名写法 -->
<!-- sqlMapConfig.xml -->
<typeAliases>
	<typeAlias type="com.jerry.domain.User" alias="user"></typeAliase>
</typeAliases>

<!-- UserMapper.xml -->
<select id="findAll" resultType="user">
	select * from User
</select>

基本的数据类型Mybatis已经设置好了

  1. java.lang.String => string
  2. java.Lang.Long => long
  3. …int,double等

Mybatis相应API


1. SqlSession工厂构建器SqlSessionFactoryBuilder

常用API:

// 通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象
String resource = "org/mybatis/builder/mybatis-config.xml"; 
// Resources工具类在ibatis.io包中, 帮助加载资源文件
InputStream inputStream = Resources.getResourceAsStream(resource); 
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 
SqlSessionFactory factory = builder.build(inputStream);

2. SqlSession工厂对象SqlSessionFactory

SqlSessionFactory创建SqlSession实例的方法:

  1. sqlSessionFactory.openSession(); => 默认开启一个事务,不会自动提交
  2. sqlSessionFactory.openSession(boolean autoCommit); => 如果参数为true,自动提交事务

3. SqlSession会话对象

// 执行的主要方法
<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层实现


1. 传统开发方式

  1. 编写Dao接口
  2. 编写Dao实现
  3. 测试
public interface UserDao {
    List<User> findAll() throws IOException;
}
public class UserDaoImpl implements UserDao {
    public List<User> findAll() 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");
        sqlSession.close();
        return userList;
    }
}
@Test
public void testTraditionDao() throws IOException {
    UserDao userDao = new UserDaoImpl();
    List<User> all = userDao.findAll();
    System.out.println(all);
}

2. 代理开发方式

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的类型相同
// mapper接口
public interface UserMapper {
	public User findById(int id);
}
					<!-- 全限定名 -->
<mapper namespace="com.jerry.mapper.UserMapper">
	<!--		方法名					参数类型		返回值类型 -->
	<select id="findByid" parameterType="int" resultType="user">
		select * from User where id = #{id}
	</select>
</mapper>

测试代理方法:

@Test
public void testProxyDao() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获得MyBatis框架生成的UserMapper接口的实现类
  	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
}

MyBatis映射文件深入


1. 动态sql语句

1. 动态sql 的<if>标签

我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。

<select id="findByCondition" parameterType="user" resultType="user">
    select * from User
    <!-- where标签会自动判断后面有没有语句,如果有就在from user后加上where,没有就不加 -->
    <where>
    	<!--if条件成立拼接 -->
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
    </where>
</select>

2. 动态sql 的<foreach>标签

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

<select id="findByIds" parameterType="list" resultType="user">
    select * from User
    <where>
    	<!-- collection标注集合是谁,user的哪个属性 -->
    	<!-- open开头 close结尾 item是集合中的每一项 separator是分隔符 -->
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

注意:collection的值虽然是传入参数的其中一个属性,但是不要写#{}

2. SQL片段抽取

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

<!--抽取sql片段简化编写-->
<sql id="selectUser">select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
    <include refid="selectUser"></include> where id=#{id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
    <include refid="selectUser"></include>
    <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

Mybatis核心配置文件深入


1. typeHandlers标签

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。

1. 开发步骤

  1. 定义转换类继承类BaseTypeHandler<T> 或者实现TypeHandler接口
  2. 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
  3. 在MyBatis核心配置文件sqlMapConfig.xml中进行注册

2. 代码实现

public class MyDateTypeHandler extends BaseTypeHandler<Date> {
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) {
        preparedStatement.setString(i,date.getTime()+"");
    }
    public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return new Date(resultSet.getLong(s));
    }
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return new Date(resultSet.getLong(i));
    }
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return callableStatement.getDate(i);
    }
}
<!--注册类型自定义转换器-->
<typeHandlers>
    <typeHandler handler="com.jerry.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

2. plugins标签

MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据,其余的插件可以类比做

1. 开发步骤

  1. 导入通用PageHelper的坐标
  2. 在mybatis核心配置文件中配置PageHelper插件
  3. 测试分页数据获取

2. 代码实现

<!-- 分页助手 -->
<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>
<!-- 注意:分页助手的插件  配置在mapper之前 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
    <!-- 指定方言 -->
    <property name="dialect" value="mysql"/>
</plugin>
// 测试
@Test
public void testPageHelper(){
    //设置分页参数
    PageHelper.startPage(1,2); // 从第一页开始,每页两条

    List<User> select = userMapper2.select(null);
    for(User user : select){
        System.out.println(user);
    }
}

//其他分页的数据
PageInfo<User> pageInfo = new PageInfo<User>(select);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页:"+pageInfo.getPageNum());
System.out.println("每页显示长度:"+pageInfo.getPageSize());
System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
System.out.println("是否最后一页:"+pageInfo.isIsLastPage());

Mybatis多表查询


1. 一对一查询

  1. 场景:用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户(可以有多个,这里为了创造一个场景)。查询一个订单,与此同时查询出该订单所属的用户。
  2. 语句:select * from orders o,user u where o.uid=u.id;
  3. 创建订单Order和用户User实体
// 没写getter和setetr和toString方法
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表当前订单从属于哪一个客户
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;

}
  1. 创建OrderMapper接口
public interface OrderMapper {
    List<Order> findAll();
}
  1. 配置OrderMapper.xml
<mapper namespace="com.jerry.mapper.OrderMapper">
    <resultMap id="orderMap" type="com.jerry.domain.Order">
    	<!-- 普通属性会正常找到,user属性是个实体引用,找不到,单独配置 -->
    	<!-- column是数据库表的列名 property是实体属性 -->
        <result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>
    </resultMap>
    			<!-- 将resultType改为resultMap -->
    <select id="findAll" resultMap="orderMap">
        select * from orders o,user u where o.uid=u.id
    </select>
</mapper>
<!-- 另一种配置方法 -->
<resultMap id="orderMap" type="com.jerry.domain.Order">
    <result property="id" column="id"></result>
    <result property="ordertime" column="ordertime"></result>
    <result property="total" column="total"></result>
    <!-- 将User对象单独配置 property是属性名 javaType是类型 -->
    <association property="user" javaType="com.jerry.domain.User">
        <result column="uid" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
    </association>
</resultMap>

2. 一对多查询

  1. 场景:用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。查询一个用户,与此同时查询出该用户具有的订单
  2. 语句:select *,o.id oid from user u left join orders o on u.id=o.uid;
  3. 实体类修改:
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表当前订单从属于哪一个客户
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表当前用户具备哪些订单
    private List<Order> orderList;
}
  1. UserMapper接口
public interface UserMapper {
    List<User> findAll();
}
  1. 配置UserMapper.xml
<mapper namespace="com.jerry.mapper.UserMapper">
    <resultMap id="userMap" type="com.jerry.domain.User">
        <result column="id" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <!-- 将association换成collection即可 -->
        <collection property="orderList" ofType="com.jerry.domain.Order">
            <result column="oid" property="id"></result>
            <result column="ordertime" property="ordertime"></result>
            <result column="total" property="total"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userMap">
        select *,o.id oid from user u left join orders o on u.id=o.uid
    </select>
</mapper>

3. 多对多查询

  1. 场景:用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用。查询用户同时查询出该用户的所有角色
  2. 语句:select u.,r.,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id;
  3. 创建实体类:
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表当前用户具备哪些订单
    private List<Order> orderList;
    //代表当前用户具备哪些角色
    private List<Role> roleList;
}

public class Role { // 角色

    private int id;
    private String rolename;

}
  1. 添加UserMapper接口方法
List<User> findAllUserAndRole();
  1. 配置UserMapper.xml
<resultMap id="userRoleMap" type="com.jerry.domain.User">
    <result column="id" property="id"></result>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <!-- 其实和一对多一样的写法,sql语句不一样 -->
    <collection property="roleList" ofType="com.jerry.domain.Role">
        <result column="rid" property="id"></result>
        <result column="rolename" property="rolename"></result>
    </collection>
</resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
    select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id
</select>

Mybatis的注解开发


1. Mybatis的常用注解

注解可以减少编写Mapper.xml
注解:

  1. @Insert:实现新增
  2. @Update:实现更新
  3. @Delete:实现删除
  4. @Select:实现查询
  5. @Result:实现结果集封装
  6. @Results:可以与@Result 一起使用,封装多个结果集
  7. @One:实现一对一结果集封装
  8. @Many:实现一对多结果集封装

2. Mybatis的增删改查

// 完成增删改查的代码
private UserMapper userMapper;

// 提取userMapper
@Before
public void before() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    userMapper = sqlSession.getMapper(UserMapper.class);
}

@Test
public void testAdd() {
    User user = new User();
    user.setUsername("测试数据");
    user.setPassword("123");
    user.setBirthday(new Date());
    userMapper.add(user);
}
@Test
public void testUpdate() throws IOException {
    User user = new User();
    user.setId(16);
    user.setUsername("测试数据修改");
    user.setPassword("abc");
    user.setBirthday(new Date());
    userMapper.update(user);
}

@Test
public void testDelete() throws IOException {
    userMapper.delete(16);
}
@Test
public void testFindById() throws IOException {
    User user = userMapper.findById(1);
    System.out.println(user);
}
@Test
public void testFindAll() throws IOException {
    List<User> all = userMapper.findAll();
    for(User user : all){
        System.out.println(user);
    }
}

使用注解代替映射文件,我们只需要加载使用了注解的Mapper接口即可

<!-- 下面两种都可以 -->

<mappers>
    <!-- 扫描使用注解的类 -->
    <mapper class="com.jerry.mapper.UserMapper"></mapper>
</mappers>

<mappers>
    <!--扫描使用注解的类所在的包-->
    <package name="com.jerry.mapper"></package>
</mappers>

3. Mybatis的注解实现复杂映射开发

实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,使用注解开发后,我们可以使用@Results注解,@Result注解,@One注解,@Many注解组合完成复杂关系的配置

注解说明
@Results代替<resultMap>,内部可以使用单个<Result>注解,
也可以使用<Result>集合
使用格式:@Results(@Result()) 或 @Results({@Result(), @Result})
@Result代替<id>和<result>标签
内部属性:
1. column:数据库列名
2. property:需要配置的属性名
3. one:需要使用@One注解
4. many:需要使用@Many注解
@One代替<assocation>标签,在注解中指定子查询返回单一对象
属性介绍:select:指定多表查询的sqlMapper
@Many代替<collection>标签,在注解中指定子查询返回对象集合

4. 一对一查询

  1. 场景:用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。查询一个订单,与此同时查询出该订单所属的用户
  2. 语句:
// 分为两步,先查询订单,通过订单表的外键查询用户
select * from orders;
select * from user where id=查询出订单的uid;
  1. 创建Order和User实体
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表当前订单从属于哪一个客户
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;

}
  1. 创建OrderMapper接口
public interface OrderMapper {
    List<Order> findAll();
}
  1. 使用注解配置Mapper(之前使用OrderMapper.xml)
public interface OrderMapper {
    @Select("select * from orders") // select语句
    @Results({ // 语句,配置多个属性要用一个数组
            @Result(id=true,property = "id",column = "id"), // id=true代表这个是主键
            @Result(property = "ordertime",column = "ordertime"),
            @Result(property = "total",column = "total"),
            @Result(property = "user", // property属性名,返回的Order内部的属性
            		column = "uid",  // 数据表的列名
                    javaType = User.class, // 映射出的类型的字节码
                    one = @One(select = // 固定语法one=@One,select后面跟着的是子查询语句的Mapper,即第二步的第二个代码。
                    "com.jerry.mapper.UserMapper.findById")) // com.jerry.mapper.UserMapper是下面代码段这个借口,findById是那个方法名,执行的是@Select注解
    })
    List<Order> findAll();
}
public interface UserMapper {
    @Select("select * from user where id=#{id}")
    User findById(int id);   
}

5. 一对多查询

  1. 场景:用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。查询一个用户,与此同时查询出该用户具有的订单
  2. 语句:
select * from user;
select * from orders where uid=查询出用户的id;
  1. 修改User实体类:
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表当前订单从属于哪一个客户
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表当前用户具备哪些订单
    private List<Order> orderList;
}
  1. 添加UserMapper接口的方法
List<User> findAllUserAndOrder();
  1. 配置Mapper
public interface UserMapper {
    @Select("select * from user")
    @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.jerry.mapper.OrderMapper.findByUid"))
    })
    List<User> findAllUserAndOrder();
}

public interface OrderMapper {
    @Select("select * from orders where uid=#{uid}")
    List<Order> findByUid(int uid);

}

6. 多对多查询

  1. 场景:用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用。查询用户同时查询出该用户的所有角色
  2. 语句:
select * from user;
select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=用户的id
  1. 创建Role实体类,修改User实体类
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表当前用户具备哪些订单
    private List<Order> orderList;
    //代表当前用户具备哪些角色
    private List<Role> roleList;
}

public class Role {

    private int id;
    private String rolename;

}
  1. 添加UserMapper接口方法
List<User> findAllUserAndRole();
  1. 使用注解配置Mapper
// 和一对多一样,除了sql语句
public interface UserMapper {
    @Select("select * from user")
    @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.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();}



public interface RoleMapper {
    @Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
    List<Role> findByUid(int uid);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值