MyBatis注解开发

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: MyBatis注解开发

在这里插入图片描述

🍁博客主页:👉 不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉 MyBatis详解
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!

在这里插入图片描述

一、mybatis注解完成基本的增删改查

1.常用的注解

  • 注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了
  • @Insert:实现新增
  • @Update:实现更新
  • @Delete:实现删除
  • @Select:实现查询
  • @Result:实现结果集封装
  • @Results:可以与@Result一起使用,封装多个结果集
  • @One:实现一对一结果集封装
  • @Many:实现一对多结果集封装

2.增删改查

 @Insert(" insert into users values(#{id},#{username},#{password},#{birthday})")
    public void save(User user);
    @Update("  update users set username=#{username},password=#{password},birthday=#{birthday} where id=#{id}")
    public void update(User user);
    @Delete(" delete from users where id=#{id}")
    public void delete(int id);
    @Select(" select * from users where id=#{id}")
    public User findById(int id);
    @Select("    select * from users")
    public List<User> findAll();

二、mybatis注解实现复杂的映射开发

  • @Results

    • 代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集合。
    • 使用格式: @Results ({@Result () ,@Result () })或@Results (@Result () )代替了标签和标签
  • @Resut

    • Result中属性介绍:
    • column:数据库的列名
    • property:需要装配的属性名
    • one:需要使用的@One注解(@Result (one=@one)() ) )
    • many:需要使用的@Many注解(@Result (many=@many)() ) )
  • @One (一对一)

    • 代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
    • One注解属性介绍:
    • select:指定用来多表查询的sqlmapper
    • 使用格式:@Result(column=" ",property="".one=@One(select=""))
  • @ Many(多对一)

    • 代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
    • 使用格式:@Result(property="".column="".many=@Many(select=""))

1.一对一的注解开发

 @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
    @Results({
            @Result(column = "oid",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.jkj.dao.UserMapper.findById")
            )
    })

   /* @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
    @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"),
            @Result(column = "birthday",property = "user.birthday")
    })*/
    public List<Order> findAll();

2.一对多的注解开发

OrderMapper

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

UserMapper

@Select("select * from users")
    @Results({
            @Result(id=true,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.jkj.dao.OrderMapper.findByUid")
            )
    })
    public List<User> findUsersAndOrdersAll();

3.多对多的注解开发

RoleMapper

  @Select("select * from users_roles ur,roles r where ur.rolesId=r.id and ur.usersId=#{uid}")
    public List<Role> findByUid(int id);

UserMapper


    @Select("select * from users")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(id=true,column = "username",property = "username"),
            @Result(id=true,column = "password",property = "password"),
            @Result(
                    property = "roleList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select ="com.jkj.dao.RoleMapper.findByUid")
            )
    })
    public List<User> findUsersAndRolesAll();

三、详细代码

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>MyBatis-Test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </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.17</version>
        </dependency>
    </dependencies>


</project>

2.jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisthree
jdbc.username=root
jdbc.password=root

3.mybatis-config.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 core file-->
       <configuration>
    <!--通过properties标签添加properties文件-->
    <properties resource="jdbc.properties"></properties>
    <!--自定义别名-->
    <typeAliases>
        <typeAlias type="com.demo.domain.User" alias="user"></typeAlias>
        <typeAlias type="com.demo.domain.Order" alias="order"></typeAlias>
        <typeAlias type="com.demo.domain.Role" alias="role"></typeAlias>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
        <package name="com.jkj.dao"/>
    </mappers>
</configuration>

4.User

package com.demo.domain;

import java.util.Date;
import java.util.List;

public class User {
    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 "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", orderList=" + orderList +
                ", roleList=" + roleList +
                '}';
    }
}

5.Order

package com.demo.domain;

import java.util.Date;

public class Order {
    private int id;
    private Date ordertime;
    private double total;
    //当前订单属于哪个用户
    private User user;

    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 getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", ordertime=" + ordertime +
                ", total=" + total +
                ", user=" + user +
                '}';
    }
}

6.Role

package com.demo.domain;

public class Role {
    private int id;
    private String roleName;
    private String roleDesc;

    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;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }
}

7.UserMapper

package com.jkj.dao;

import com.jkj.domain.Role;
import com.jkj.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    @Insert(" insert into users values(#{id},#{username},#{password},#{birthday})")
    public void save(User user);
    @Update("  update users set username=#{username},password=#{password},birthday=#{birthday} where id=#{id}")
    public void update(User user);
    @Delete(" delete from users where id=#{id}")
    public void delete(int id);
    @Select(" select * from users where id=#{id}")
    public User findById(int id);
    @Select("  select * from users")
    public List<User> findAll();

    @Select("select * from users")
    @Results({
            @Result(id=true,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.jkj.dao.OrderMapper.findByUid")
            )
    })
    public List<User> findUsersAndOrdersAll();


    @Select("select * from users")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(id=true,column = "username",property = "username"),
            @Result(id=true,column = "password",property = "password"),
            @Result(
                    property = "roleList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select ="com.jkj.dao.RoleMapper.findByUid")
            )
    })
    public List<User> findUsersAndRolesAll();

}

}

8.OrderMapper

package com.jkj.dao;

import com.jkj.domain.Order;
import com.jkj.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 orders where uid=#{uid}")
    public List<Order> findByUid(int uid);

    @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
    @Results({
            @Result(column = "oid",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.jkj.dao.UserMapper.findById")
            )
    })

   /* @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
    @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"),
            @Result(column = "birthday",property = "user.birthday")
    })*/
    public List<Order> findAll();
}

9.RoleMapper

package com.jkj.dao;

import com.jkj.domain.Role;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface RoleMapper {
    @Select("select * from users_roles ur,roles r where ur.rolesId=r.id and ur.usersId=#{uid}")
    public List<Role> findByUid(int id);
}

10.MyBatisTest

package com.jkj.test;

import com.jkj.dao.OrderMapper;
import com.jkj.dao.UserMapper;
import com.jkj.domain.Order;
import com.jkj.domain.Role;
import com.jkj.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.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest {
    private UserMapper userMapper;
    private OrderMapper orderMapper;
    private SqlSession sqlSession;
    @Before
    public void before() throws IOException {
        //1.加载MyBatis的核心配置文件获取sqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取sqlSession,执行sql
        sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(UserMapper.class);
        orderMapper = sqlSession.getMapper(OrderMapper.class);
    }
    @Test
    public void save(){
        User user=new User();
        user.setUsername("jack");
        user.setPassword("666");
        userMapper.save(user);
        sqlSession.close();
    }
    @Test
    public void update(){
        User user=new User();
        user.setId(6);
        user.setPassword("000");
        userMapper.update(user);
        sqlSession.close();
    }
    @Test
    public void delete(){
        userMapper.delete(7);
        sqlSession.close();
    }
    @Test
    public void findById(){
        User user = userMapper.findById(2);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void findAll(){
        List<User> users = userMapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void findOrderAll(){
        List<Order> orderList = orderMapper.findAll();
        for (Order orders : orderList) {
            System.out.println(orders);
        }
        sqlSession.close();
    }
    @Test
    public void findUsersAndOrdersAll(){
        List<User> userList = userMapper.findUsersAndOrdersAll();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void findUsersAndRolesAll() {
        List<User> usersAndRolesAll = userMapper.findUsersAndRolesAll();
        for (User user : usersAndRolesAll) {
            System.out.println(user);
        }

    }


}

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
4天前
|
SQL 缓存 Java
MyBatis如何关闭一级缓存(分注解和xml两种方式)
MyBatis如何关闭一级缓存(分注解和xml两种方式)
21 5
|
4天前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
22 3
|
11天前
|
SQL 存储 数据库
深入理解@TableField注解的使用-MybatisPlus教程
`@TableField`注解在MyBatis-Plus中是一个非常灵活和强大的工具,能够帮助开发者精细控制实体类与数据库表字段之间的映射关系。通过合理使用 `@TableField`注解,可以实现字段名称映射、自动填充、条件查询以及自定义类型处理等高级功能。这些功能在实际开发中,可以显著提高代码的可读性和维护性。如果需要进一步优化和管理你的MyBatis-Plus应用程
51 3
|
9天前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
30 1
|
2月前
|
SQL XML Java
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
文章介绍了MyBatis的简单增删改查操作,包括创建数据表、实体类、配置文件、Mapper接口及其XML文件,并解释了`#{}`预编译参数和`@Param`注解的使用。同时,还涵盖了resultType与resultMap的区别,并提供了完整的代码实例和测试用例。
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
|
1月前
|
前端开发 Java 数据库连接
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
本文是一份全面的表白墙/留言墙项目教程,使用SpringBoot + MyBatis技术栈和MySQL数据库开发,涵盖了项目前后端开发、数据库配置、代码实现和运行的详细步骤。
36 0
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
|
2月前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
3月前
|
SQL Java 数据库
5、Mybatis-Plus 常用注解
这篇文章详细介绍了Mybatis-Plus中常用的注解,包括解决实体类与数据库表名不一致、字段不匹配的问题,主键生成策略的配置,以及逻辑删除的实现方法。
5、Mybatis-Plus 常用注解
|
3月前
|
SQL Java 数据库连接
Spring Boot联手MyBatis,打造开发利器:从入门到精通,实战教程带你飞越编程高峰!
【8月更文挑战第29天】Spring Boot与MyBatis分别是Java快速开发和持久层框架的优秀代表。本文通过整合Spring Boot与MyBatis,展示了如何在项目中添加相关依赖、配置数据源及MyBatis,并通过实战示例介绍了实体类、Mapper接口及Controller的创建过程。通过本文,你将学会如何利用这两款工具提高开发效率,实现数据的增删查改等复杂操作,为实际项目开发提供有力支持。
144 0
|
3月前
|
SQL Java 数据库连接
后端框架的学习----mybatis框架(7、使用注解开发)
这篇文章讲述了如何使用MyBatis框架的注解方式进行开发,包括在接口上使用注解定义SQL语句,并通过动态代理实现对数据库的增删改查操作,同时强调了接口需要在核心配置文件中注册绑定。