【Spring集成MyBatis】MyBatis注解开发

文章目录

  • 1. MyBatis的常用注解
  • 2. 基于注解的MyBatis增删改查
    • 完整代码
    • 加载映射关系
    • 测试代码
  • 3. MyBatis的注解实现复杂映射开发
    • 一对一操作的实现
    • 一对一操作实现的第二种方式
    • 一对多操作的实现
    • 多对多操作实现

1. MyBatis的常用注解

【Spring集成MyBatis】MyBatis注解开发_第1张图片

2. 基于注解的MyBatis增删改查

使用注解开发,就可以删掉原本写MyBatis语句的xml文件了,注解只要在UserMapper.java接口上进行实现即可

@Insert("insert into user values(#{id}, #{username}, #{password}, #{birthday})")
void save(User user);

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

@Update("update user set username=#{username}, password=#{password}, birthday=#{birthday} where id=#{id}")
void update(User user);

@Select("select * from user where id=#{id}")
User findById(int id);

@Select("select * from user")
List<User> findAll();

完整代码

package com.example.demo.mapper;

import com.example.demo.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserMapper {


    @Insert("insert into user values(#{id}, #{username}, #{password}, #{birthday})")
    void save(User user);

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

    @Update("update user set username=#{username}, password=#{password}, birthday=#{birthday} where id=#{id}")
    void update(User user);

    @Select("select * from user where id=#{id}")
    User findById(int id);

    @Select("select * from user")
    List<User> findAll();
}

加载映射关系

原本在sqlMapConfig.xml文件中的加载映射文件修改为加载映射关系:


<mappers>
    <package name="com.example.demo.mapper"/>
mappers>

测试代码

原本数据库中的内容:
【Spring集成MyBatis】MyBatis注解开发_第2张图片

package com.example.demo;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class DemoApplication {

    public static void main(String[] args) throws IOException {
//        1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//        3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//        4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        增加User信息
        User saveUser = new User();
        saveUser.setUsername("newUser");
        saveUser.setPassword("aaaaaa");
        saveUser.setBirthday(new Date());
        mapper.save(saveUser);
//        删除User信息
        int deleteUserId = 3;
        mapper.delete(deleteUserId);
//        修改User信息
        User updateUser = new User();
        updateUser.setId(2);
        updateUser.setUsername("ccc");
        updateUser.setPassword("1234567update");
        mapper.update(updateUser);
//        根据Id查询User
        User user = mapper.findById(1);
        System.out.println(user);
//        查询所有user
        List<User> userList = mapper.findAll();
        System.out.println(userList);

        sqlSession.commit();

//        6. 释放资源
        sqlSession.close();

    }
}

打印的信息:
在这里插入图片描述

更新后的内容:
【Spring集成MyBatis】MyBatis注解开发_第3张图片

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

【Spring集成MyBatis】MyBatis注解开发_第4张图片
此处对应于【Spring集成MyBatis】MyBatis的多表查询的内容,来写一下对应的注解实现。

一对一操作的实现

原本基于配置是这么写的


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.OrderMapper">
    
    <resultMap id="orderMap" type="com.example.demo.domain.Order">



        <id column="oid" property="id">id>
        <result column="ordertime" property="orderTime">result>
        <result column="total" property="total">result>
        <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>

    <select id="findAll" resultMap="orderMap">
        SELECT *, o.id `orderid`, u.id `userid` FROM `order` o, `user` u WHERE o.uid=u.id
    select>

mapper>

使用注解后如下修改

package com.example.demo.mapper;

import com.example.demo.domain.Order;
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 *, o.id oid from `order` o, user u where o.uid=u.id")
    @Results({
            @Result(column = "oid", property = "id"),
            @Result(column = "ordertime", property = "orderTime"),
            @Result(column = "total", property = "total"),
            @Result(column = "uid", property = "user.id"),
            @Result(column = "username", property = "user.username"),
            @Result(column = "password", property = "user.password")
    })
    List<Order> findAll();

}

一对一操作实现的第二种方式

其中,在要封装的User对象中,我们可以在@Result注解中写明属性名称、数据库查询到的值、要封装的实体类型等等等,有点类似于之前的注解中的那些属性,不同的事这里通过一个@One来指定通过哪个接口的方法来获得对应的数据,这时候会将column的值注入到这个方法中来获得具体的结果
也就是,首先使用

select * from `order`

来查询出order下的所有信息,包括id、ordertime、total、uid,接着,我们需要根据里面的uid可以查出对应的User信息并封装到Order实体类下的user属性中

select * from `user` where id=(上面查询结果的所有uid)

这里就需要在@Result注解中进一步指定property、column、javaType、one(由于是一对一所以使用one,一对多使用many)

package com.example.demo.mapper;

import com.example.demo.domain.Order;
import com.example.demo.domain.User;
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 `order`")
    @Results({
            @Result(column = "id", property = "id"),
            @Result(column = "ordertime", property = "orderTime"),
            @Result(column = "total", property = "total"),
            @Result(
                    property = "user", // 要封装的属性名称
                    column = "uid", // 根据哪个字段去查询user表的数值
                    javaType = User.class, // 要封装的实体类型
                    // select属性 代表查询哪个接口的方法获得数据
                    one = @One(select = "com.example.demo.mapper.UserMapper.findById")
            )
    })
    List<Order> findAll();

}

以上两种一对一操作的测试代码:

package com.example.demo;

import com.example.demo.domain.Order;
import com.example.demo.domain.User;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class DemoApplication {

    public static void main(String[] args) throws IOException {
//        1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//        3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//        4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
        List<Order> orderList = orderMapper.findAll();
        for (Order order : orderList) {
            System.out.println(order);
        }

//        6. 释放资源
        sqlSession.close();

    }
}

结果:
在这里插入图片描述

一对多操作的实现

查询User对应的订单,和【Spring集成MyBatis】MyBatis的多表查询中一样,首先需要再User里面加上一个orderList属性,用于封装所有的订单,并写好对应的set、get方法以及对应的toString方法。
类似于一对一操作的第二种实现方式,我们需要在@Result里面指定property、column、javaType,由于返回的是List,就不用one而用many
首先查询出所有的用户,并在用户下面封装其订单列表。
通过

select * from user

查出了用户的id,username,password,birthday的信息,我们需要根据里面的id到order表里查询对应的订单

select * from `order` where uid=(上面user查询出来的所有id)

即再通过一个@Result注解指定根据uid查询订单的方法。目前Order类里还没有根据uid查询订单的方法,所以我们需要再去实现一下根据uid查询订单的方法
在OrderMapper里写:

@Select("select * from `order` where uid=#{id}")
List<Order> findByUid(int id);

在UserMapper里写根据userid查询指定订单

@Select("select * from user")
@Results({
        @Result(column = "id", property = "id"),
        @Result(column = "username", property = "username"),
        @Result(column = "password", property = "password"),
        @Result(column = "birthday", property = "birthday"),
        @Result(
                property = "orderList",
                column = "id",
                javaType = List.class,
                many = @Many(select = "com.example.demo.OrderMapper.findByUid")
        )
})
List<User> findUserAndOrderAll();

测试:

package com.example.demo;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.List;

public class DemoApplication {

    public static void main(String[] args) throws IOException {
//        1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//        3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//        4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.findUserAndOrderAll();
        for (User user : userList) {
            System.out.println(user);
        }

//        6. 释放资源
        sqlSession.close();

    }
}

查询出来的结果如下:
在这里插入图片描述

多对多操作实现

查询User对应的角色,和【Spring集成MyBatis】MyBatis的多表查询中一样,首先需要再User里面加上一个roleList属性,用于封装所有的角色,并写好对应的set、get方法以及对应的toString方法。
实现过程如下:
先查询所有的User信息

select * from USER

根据userid查询所有的对应的role及其信息

select * from user_role ur, role r where ur.roleId=r.id and userid=(上面查出来的所有id)

那么首先我们需要建立roleMapper,并在RoleMapper中写上对应的查询语句:

package com.example.demo.mapper;

import com.example.demo.domain.Role;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface RoleMapper {

    @Select("select * from user_role ur, role r where ur.roleId=r.id and userid=#{id}")
    List<Role> findByUid(int id);
}

接着,在UserMapper中类似一对多一样补充如下方法:

@Select("select * from User")
@Results({
        @Result(column = "id", property = "id"),
        @Result(column = "username", property = "username"),
        @Result(column = "password", property = "password"),
        @Result(column = "birthday", property = "birthday"),
        @Result(
                property = "roleList",
                column = "id",
                javaType = List.class,
                many = @Many(select = "com.example.demo.mapper.RoleMapper.findByUid")
        )
})
List<User> findUserAndRoleAll();

最后测试:

package com.example.demo;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.util.List;

public class DemoApplication {

    public static void main(String[] args) throws IOException {
//        1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//        3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//        4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.findUserAndRoleAll();
        for (User user : userList) {
            System.out.println(user);
        }

//        6. 释放资源
        sqlSession.close();

    }
}

结果如下:
在这里插入图片描述

你可能感兴趣的:(Spring,spring,mybatis,java)