003 mapper代理开发方式-注解方式

文章目录

开发方式
只需要编写mapper接口文件接口。

AnnotationUserMapper.java

java 复制代码
package com.xd.mybatisdemo.mapper;

import com.xd.mybatisdemo.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;

import java.util.List;

public interface AnnotationUserMapper {
    // 查询
    @Select("SELECT * FROM user WHERE id = #{id}")
    public User findUserById(int id);

    // 模糊查询用户列表
    @Select("SELECT * FROM user WHERE username LIKE '%${value}%'")
    public List<User> findUserList(String username);
// 添加并实现主键返回

    @Insert("INSERT INTO user (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})")
    @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id",
            resultType = int.class, before = false)
    public void insertUser(User user);
}

User.java

java 复制代码
package com.xd.mybatisdemo.pojo;

import java.util.Date;

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

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

db.properties

properties 复制代码
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/mybatisdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
db.username=root
db.password=root

SqlMapConfig.xml

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>
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.xd.mybatisdemo.mapper.AnnotationUserMapper"/>
    </mappers>
</configuration>

AnnotationUserMapperTest.java

java 复制代码
package com.xd.mybatisdemo;

import com.xd.mybatisdemo.mapper.AnnotationUserMapper;
import com.xd.mybatisdemo.pojo.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.InputStream;
import java.util.List;

public class AnnotationUserMapperTest {
    private SqlSessionFactory sqlSessionFactory;

    /**
     * @throws Exception
     * @Before注解的方法会在@Test注解的方法之前执行
     */
    @Before
    public void init() throws Exception {
// 指定全局配置文件路径
        String resource = "SqlMapConfig.xml";
// 加载资源文件(全局配置文件和映射文件)
        InputStream inputStream = Resources.getResourceAsStream(resource);
// 还有构建者模式,去创建SqlSessionFactory对象
        sqlSessionFactory = new
                SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testFindUserById() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        AnnotationUserMapper userMapper =
                sqlSession.getMapper(AnnotationUserMapper.class);
        User user = userMapper.findUserById(1);
        System.out.println(user.getUsername());
    }

    @Test
    public void testFindUserList() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        AnnotationUserMapper userMapper =
                sqlSession.getMapper(AnnotationUserMapper.class);
        List<User> list = userMapper.findUserList("老郭");
        System.out.println(list);
    }

    @Test
    public void testInsertUser() {
        SqlSession sqlSession = null;


        try {
            sqlSession = sqlSessionFactory.openSession();
            AnnotationUserMapper userMapper =
                    sqlSession.getMapper(AnnotationUserMapper.class);


            User user = new User();
            user.setUsername("张五");
            user.setSex("1");
            user.setAddress("ccccc");
            userMapper.insertUser(user);
            sqlSession.commit(); // 提交事务
            System.out.println(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            if (sqlSession != null) {
                sqlSession.rollback(); // 发生异常时回滚事务
            }
        } finally {
            if (sqlSession != null) {
                sqlSession.close(); // 关闭 SqlSession
            }

        }
    }
}

pom.xml

xml 复制代码
<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>mybatisdemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mybatisdemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <!-- mysql依赖 -->
<!--    <dependency>-->
<!--      <groupId>mysql</groupId>-->
<!--      <artifactId>mysql-connector-java</artifactId>-->
<!--      <version>5.1.35</version>-->
<!--    </dependency>-->


    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <version>8.0.32</version>
    </dependency>

    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>
</project>

user.sql

sql 复制代码
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `birthday` date NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '老郭', '2024-12-17', '男', 'aaa');
INSERT INTO `user` VALUES (2, '张三', '2024-12-10', '女', 'ccc');
INSERT INTO `user` VALUES (3, '李四', '2024-12-19', '女', 'ddd');
INSERT INTO `user` VALUES (4, '老郭', '2024-12-20', '男', 'eee');

SET FOREIGN_KEY_CHECKS = 1;
相关推荐
码农幻想梦1 天前
实验七 带函数查询和综合查询(2)
数据库·sql·mybatis
要开心吖ZSH2 天前
关于使用Mybatis-plus的TableNameHandler动态表名处理器实现分表业务的详细介绍
java·mybatis
有你有我OK2 天前
mybatis sql 拦截器
java·sql·mybatis
上不如老下不如小3 天前
Spring整合Mybatis、junit纯注解
spring·junit·mybatis
NiNg_1_2343 天前
MyBatis和JPA区别详解
mybatis·jpa
huang_hai_an3 天前
MyBatis 写法
mybatis
中國移动丶移不动4 天前
Java 反射与动态代理:实践中的应用与陷阱
java·spring boot·后端·spring·mybatis·hibernate
A阳俊yi4 天前
Mybatis——sql映射文件中的增删查改
mybatis
是小崔啊5 天前
Spring Boot - 数据库集成03 - 集成Mybatis
数据库·spring boot·mybatis