万隆的笔记 万隆的笔记
博文索引
笔试面试
  • 在线学站

    • 菜鸟教程 (opens new window)
    • 入门教程 (opens new window)
    • Coursera (opens new window)
  • 在线文档

    • w3school (opens new window)
    • Bootstrap (opens new window)
    • Vue (opens new window)
    • 阿里开发者藏经阁 (opens new window)
  • 在线工具

    • tool 工具集 (opens new window)
    • bejson 工具集 (opens new window)
    • 文档转换 (opens new window)
  • 更多在线资源
  • Changlog
  • Aboutme
GitHub (opens new window)
博文索引
笔试面试
  • 在线学站

    • 菜鸟教程 (opens new window)
    • 入门教程 (opens new window)
    • Coursera (opens new window)
  • 在线文档

    • w3school (opens new window)
    • Bootstrap (opens new window)
    • Vue (opens new window)
    • 阿里开发者藏经阁 (opens new window)
  • 在线工具

    • tool 工具集 (opens new window)
    • bejson 工具集 (opens new window)
    • 文档转换 (opens new window)
  • 更多在线资源
  • Changlog
  • Aboutme
GitHub (opens new window)
  • MyBatis

    • MyBatis 简介
    • MyBatis简单应用
    • MyBatis常⽤配置
    • MyBatis 单表 CRUD 操作
    • MyBatis动态 SQL
    • MyBatis复杂映射
    • MyBatis注解开发
      • 简单增删查改
      • 复杂映射开发
    • MyBatis缓存
    • MyBatis插件
    • ⾃定义持久层框架
    • MyBatis架构原理
    • MyBatis源码剖析
    • MyBatis设计模式
  • Spring-MyBatis

  • MyBatis-Plus

  • MyBatis
  • MyBatis
2022-11-06
目录

MyBatis注解开发

# MyBatis注解开发

随着这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了。常用注解有:

注解 说明
@Insert 新增
@Update 更新
@Delete 删除
@Select 查询
@Result 结果集封装
@Results 与@Result 一起使用,封装多个结果集
@One 一对一结果集封装
@Many 一对多结果集封装

# 简单增删查改

使用注解开发,配置方式与MyBatis简单应用无异,仅是将Mapper映射文件sql的编写转义到了注解中,这里同样以user表为例子,仅展示示例的注解写法,其他配置不作详细说明:

@Select("select * from User")
List<User> findAll();
@Insert("insert into user(username, password) values(#{username}, #{password})")
Integer add(User user);
@Update("update user set username = #{username}, password = #{password} where id = #{id}")
Integer update(User user);
@Delete("delete from user where id= #{id}")
Integer deleteById(Integer id);

测试用例:

public class MyBatisAnnotationTest {

    private UserMapper userMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {
        // 加载核⼼配置⽂件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 获得sqlSession⼯⼚对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // 获得sqlSession对象
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void after() {
        // 释放资源
        sqlSession.close();
    }

    @Test
    public void testSelectAll() {
        // 执⾏sql语句
        List<User> userList = userMapper.findAll();
        // 打印结果
        System.out.println(userList);
    }

    @Test
    public void testAdd() {
        User user = new User();
        user.setUsername("jacky_2");
        user.setPassword("123456");
        // 执⾏sql语句
        int insert = userMapper.add(user);
        System.out.println(insert);
        sqlSession.commit();
    }

    @Test
    public void testUpdate() {
        User user = new User();
        user.setId(4);
        user.setUsername("jacky_2");
        user.setPassword("1234567");
        // 执⾏sql语句
        int update = userMapper.update( user);
        System.out.println(update);
        sqlSession.commit();
    }

    @Test
    public void testDeleted() {
        int delete = userMapper.deleteById(4);
        System.out.println(delete);
        sqlSession.commit();
    }

}

# 复杂映射开发

除了在映射文件中通过配置来实现复杂映射,我们还可以使用 @Results、@Result、@One、@Many这些注解组合完成复杂关系的配置。

注解 说明
@Results 代替的是标签<resultMap>。该注解中可以使用单个@Result注解,也可以使用@Result集合。使用格式:
@Results ( (@Result () [ , @Result () ] ...) )
@Resut 代替了<id>标签和<result>标签
属性介绍:
- column:数据库的列名
- property:需要装配的属性名
- one:需要使用的 @One 注解 (@Result (one=@one) ( ) )
- many:需要使用的@Many 注解 (@Result (many=@many) ( ) )
@One( 一对一。代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
属性介绍:
- select: 指定用来多表查询的 sql mapper
使用格式:@Result( column=" ", property= ", one=@One(select=""))
@Many 多对一。代替了<collection>标签,是多表查询的关键,在注解中用来指定子查询返回对象集合。
使用格式:@Result(property="",column="", many=@Many (select=""))

这里展示前文Mybatis复杂映射模型改成注解的方式:

# 一对一

public interface OrderMapper {

    @Select("select * from orders")
    @Results({
            @Result(id=true, property = "id", column = "id"),
            @Result(property = "orderNo",column = "order_no"),
            @Result(property = "amount",column = "amount"),
            @Result(property = "user", column = "uid", javaType = User.class,
                    one = @One(select="org.example.hello.mybatis.mapper.UserMapper.findById"))
    })
    List<Order> findAll();

}

public interface UserMapper {

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

}

# 一对多

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 = "orderList", column = "id", javaType = List.class,
                    many = @Many(select = "org.example.hello.mybatis.mapper.OrderMapper.findByUid"))
    })
    List<User> findAllWithOrders();

}

public interface OrderMapper {

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

# 多对多

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 = "roleList", column = "id", javaType = List.class,
                    many = @Many(select = "org.example.hello.mybatis.mapper.RoleMapper.findByUid"))
    })
    List<User> findAllWithRoles();

}
public interface RoleMapper {

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

}
上次更新: 5/30/2023, 10:53:02 PM
MyBatis缓存

MyBatis缓存→

最近更新
01
2025
01-15
02
Elasticsearch面试题
07-17
03
Elasticsearch进阶
07-16
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式