当前位置: 首页 > article >正文

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

文章目录

    • AnnotationUserMapper.java
    • User.java
    • db.properties
    • SqlMapConfig.xml
    • AnnotationUserMapperTest.java
    • pom.xml
    • user.sql

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

AnnotationUserMapper.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

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

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

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

<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

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;


http://www.kler.cn/a/524537.html

相关文章:

  • ASP.NET代码审计 SQL注入篇(简单记录)
  • C++ ——— 仿函数
  • CMAKE工程编译好后自动把可执行文件传输到远程开发板
  • Nginx前端后端共用一个域名如何配置
  • 【C++】特殊类设计、单例模式与类型转换
  • [权限提升] Windows 提权 — 系统内核溢出漏洞提权
  • 64位的谷歌浏览器Chrome/Google Chrome
  • Maven项目JUnit测试的远程调试技巧
  • 深度学习中常用的评价指标方法
  • 剑指 Offer II 002. 二进制加法
  • 探索高效图像识别:基于OpenCV的形状匹配利器
  • git中有关old mode 100644、new mode 10075的问题解决小结
  • EtherCAT主站IGH-- 19 -- IGH之fsm_pdo.h/c文件解析
  • DeepSeek R1有什么不同
  • H264原始码流格式分析
  • 探索AI(chatgpt、文心一言、kimi等)提示词的奥秘
  • 【2024年华为OD机试】(C卷,200分)- 最长子字符串的长度(二) (JavaScriptJava PythonC/C++)
  • 自由窗口边框阴影描绘方案汇总-社群讨论学习
  • AUTOSAR从入门到精通-高级驾驶辅助系统(ADAS)
  • 数据结构的队列
  • Helm Chart 实战指南
  • 菜鸟之路Day05一一正则表达式
  • js笔记(黑马程序员)
  • DeepSeek模型:开启人工智能的新篇章
  • Spring Boot - 数据库集成05 - 集成MongoDB
  • Vue+Echarts 实现青岛自定义样式地图