MyBatis常用注解及基本增删改查的注解实现

Terwer 后端开发 MyBatis评论155字数 3910阅读13分2秒阅读模式
摘要

本文介绍了 MyBatis 常用注解和增删改查操作,包括 @Insert、@Update、@Delete、@Select 等注解的用法,以及数据库配置、实体类 User 和 UserMapper 的示例代码。

MyBatis 的常用注解

注解可以减少 Mapper 文件的编写,常用注解如下:文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Insert:实现新增文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Update:实现更新文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Delete:实现删除文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Select:实现查询文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Result:实现结果集封装文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Results:可以和 @Result 一起使用,封装多个结果集文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@One:实现一对一结果集封装文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

@Many:实现多对多结果集封装文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

MyBatis 的增删改查

数据库配置依旧保存不变文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

jdbc.properties文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

# 新版驱动名称发生了改变
# jdbc.driver=com.mysql.jdbc.Driver
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
jdbc.username=terwer
jdbc.password=123456

sqlMapConfig.xml文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 加载外部的 propeties 文件 -->
    <properties resource="jdbc.properties"/>

    <settings>
        <!-- 输出日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <!-- 为实体的全限定类名取别名 -->
    <typeAliases>
        <!-- 给单独的实体起别名 -->
        <!-- <typeAlias type="com.terwergreen.pojo.User" alias="user"/> -->

        <!-- 批量起别名:改包下所有类本身的类名,不区分大小写 -->
        <package name="com.terwergreen.pojo"/> 
    </typeAliases>

    <!-- environments:运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 当前事务交给 JDBC 管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 当前使用 MyBatis 提供的连接池 -->
            <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>
        <environment id="production">
            <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="OrderMapper.xml"/>
        -->
        <package name="com.terwergreen.mapper"/>
    </mappers>
</configuration>

User文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

public class User {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\''
                '}';
    }
}

UserMapper文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

/**
 * 用户映射
 *
 * @name: UserMapper
 * @author: terwer
 * @date: 2022-05-25 13:27
 **/
public interface UserMapper {
    @Select("select * from user")
    List<User> findAll();

    @Insert("insert into user(username) values(#{username})")
    void add(User user);

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

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

结果测试文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

UserMapper文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

public class UserMapperTest {

    private UserMapper userMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws Exception {
        System.out.println("before...");
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

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

    @Test
    public void add() throws IOException {
        User user = new User();
        user.setUsername("测试3");
        userMapper.add(user);

        // 这里一定要加,否则不会提交事务
        sqlSession.commit(true);
    }

    @Test
    public void update() {
        User user = new User();
        user.setId(3);
        user.setUsername("测试11");
        userMapper.update(user);

        // 这里一定要加,否则不会提交事务
        sqlSession.commit(true);
    }

    @Test
    public void delete() {
        userMapper.delete(3);

        // 这里一定要加,否则不会提交事务
        sqlSession.commit(true);
    }
}

注意:默认不会自动提交事务,可以手动设置 SqlSession,也可以在创建 SqlSession 的时候指定自动提交事务。文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

// sqlSession = sqlSessionFactory.openSession();
// 这样也是可以的,这样的话后面就不用每次都设置了
sqlSession = sqlSessionFactory.openSession(true);

修改 MyBatis 的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的 Mapper 接口
即可文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

<!-- 引入映射配置文件 -->
<mappers>
   <mapper class="com.terwergreen.mapper.UserMapper"/>
</mappers>

或者指定扫描包含映射关系的接口所在的包也可以文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

<!-- 引入映射配置文件 -->
<mappers>
    <package name="com.terwergreen.mapper"/>
</mappers>

本文代码地址

mybatis-annotation文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

文章更新历史文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

2022-08-30 feat:初稿 文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

本文介绍了 MyBatis 常用注解和增删改查操作,包括 @Insert、@Update、@Delete、@Select 等注解的用法,以及数据库配置、实体类 User 和 UserMapper 的示例代码。文章源自浅海拾贝-https://blog.terwergreen.com/mybatis-annotation-develop.html

相关文章
  • 扫码加我微信
  • 验证消息请输入:来自你的博客
  • weinxin
  • 我的微信公众号
  • 微信扫一扫与我交流吧
  • weinxin
Terwer
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: