Spring Boot整合Mybatis(注解版+XML版)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Spring Boot整合Mybatis(注解版+XML版)

0 Mybatis的简单介绍

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。

iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

思想:ORM:Object Relational Mapping

Mybatis基本框架:

1 环境搭建

新建Spring Boot项目,引入依赖

pom.xml
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!--Druid数据源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<!--测试-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
DB-sql
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
项目结构

2 整合方式一:注解版

2.1 配置
server:
  port: 8081
spring:
  datasource: # 配置数据库
    username: root
    password: 12345
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test   #数据库名
    type: com.alibaba.druid.pool.DruidDataSource
2.2 编码
/**
 * 注解版
 */
@Mapper
@Repository
public interface JavaStudentMapper {
    /**
     * 添加一个学生
     *
     * @param student
     * @return
     */
    @Insert("insert into student(name, age) " +
            "values (#{name}, #{age})")
    public int saveStudent(Student student);
    /**
     * 根据ID查看一名学生
     *
     * @param id
     * @return
     */
    @Select("select *  " +
            "from student " +
            "where id = #{id}")
    public Student findStudentById(Integer id);
    /**
     * 查询全部学生
     *
     * @return
     */
    @Select("select * " +
            "from student")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "age", column = "age")
    })
    public List<Student> findAllStudent();
    /**
     * 根据ID删除一个
     *
     * @param id
     * @return
     */
    @Delete("delete   " +
            "from student " +
            "where id = #{id}")
    public int removeStudentById(Integer id);
    /**
     * 根据ID修改
     *
     * @param student
     * @return
     */
    @Update("update set name=#{name},age=#{age}  " +
            "where id=#{id}")
    public int updateStudentById(Student student);
}
2.3 测试
@Autowired
private JavaStudentMapper studentMapper;
@Test
void testJavaMapperInsert() {
    Student student = new Student("张三", 22);
    System.out.println(studentMapper.saveStudent(student));
}
@Test
void testJavaMapperFind() {
    System.out.println(studentMapper.findStudentById(2));
}
@Test
void testJavaMapperFindAll() {
    System.out.println(studentMapper.findAllStudent());
}
@Test
void testJavaMapperUpdate() {
    Student student = new Student(2, "张三", 22);
    System.out.println(studentMapper.updateStudentById(student));
}
@Test
void testJavaMapperDelete() {
    System.out.println(studentMapper.removeStudentById(2));
}

3 整合方式二:XML版

3.1 配置
server:
  port: 8081
spring:
  application:
    name: hospitalManager       #项目名
  datasource: # 配置数据库
    username: root
    password: 12345
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test   #数据库名
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml #扫描resources下的mapper文件夹下的xml文件
  type-aliases-package: org.ymx.sp_mybatis.pojo #实体类所在包,定义别名

主启动类:

@SpringBootApplication
@MapperScan("org.ymx.sp_mybatis.xmlMapper") //扫描的mapper
public class SpMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpMybatisApplication.class, args);
    }
}
3.2 编码
/**
 * xml版
 */
@Mapper
@Repository
public interface XmlStudentMapper {
    /**
     * 添加一个学生
     *
     * @param student
     * @return
     */
    public int saveStudent(Student student);
    /**
     * 根据ID查看一名学生
     *
     * @param id
     * @return
     */
    public Student findStudentById(Integer id);
    /**
     * 查询全部学生
     *
     * @return
     */
    public List<Student> findAllStudent();
    /**
     * 根据ID删除一个
     *
     * @param id
     * @return
     */
    public int removeStudentById(Integer id);
    /**
     * 根据ID修改
     *
     * @param student
     * @return
     */
    public int updateStudentById(Student student);
}

xml文件(StudentMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.ymx.sp_mybatis.dao.xmlMapper.XmlStudentMapper">
    <!-- 添加学生-->
    <insert id="saveStudent" parameterType="org.ymx.sp_mybatis.pojo.Student" useGeneratedKeys="true"
            keyProperty="id">
        insert into student(name, age)
        values (#{name}, #{age})
    </insert>
    <!--查看学生根据ID-->
    <select id="findStudentById" parameterType="integer"              resultType="org.ymx.sp_mybatis.pojo.Student">
        select *
        from student
        where id = #{id}
    </select>
    <!--查看全部学生-->
    <select id="findAllStudent" resultMap="studentResult">
        select *
        from student
    </select>
    <!--删除学生根据ID-->
    <delete id="removeStudentById" parameterType="integer">
        delete
        from student
        where id = #{id}
    </delete>
    <!--修改学生根据ID-->
    <update id="updateStudentById" parameterType="org.ymx.sp_mybatis.pojo.Student">
        update student
        set name=#{name},
            age=#{age}
        where id = #{id}
    </update>
    <!--查询结果集-->
    <resultMap id="studentResult" type="org.ymx.sp_mybatis.pojo.Student">
        <result column="id" javaType="INTEGER" jdbcType="INTEGER" property="id"/>
        <result column="name" javaType="STRING" jdbcType="VARCHAR" property="name"/>
        <result column="age" javaType="INTEGER" jdbcType="INTEGER" property="age"/>
    </resultMap>
</mapper>
3.3 测试
@Autowired
private XmlStudentMapper studentMapper;
@Test
void testJavaMapperInsert() {
    Student student = new Student("张三", 22);
    System.out.println(studentMapper.saveStudent(student));
}
@Test
void testJavaMapperFind() {
    System.out.println(studentMapper.findStudentById(2));
}
@Test
void testJavaMapperFindAll() {
    System.out.println(studentMapper.findAllStudent());
}
@Test
void testJavaMapperUpdate() {
    Student student = new Student(2, "张三", 22);
    System.out.println(studentMapper.updateStudentById(student));
}
@Test
void testJavaMapperDelete() {
    System.out.println(studentMapper.removeStudentById(2));
}

4 总结

基本步骤:

注意事项:

(1)相比注解方式,更推荐使用xml方式,因为注解方式将SQL语句嵌套到Java代码中,一旦需要修改则需要重新编译项目,而xml方式则不需要重新编译项目

(2)xml方式需要在主启动函数或配置类中配置接口的扫描路径


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
17天前
|
XML Java 数据库连接
mybatis中在xml文件中通用查询结果列如何使用
mybatis中在xml文件中通用查询结果列如何使用
20 0
|
2天前
|
缓存 Java Sentinel
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
|
18天前
|
SQL XML Java
【mybatis】第二篇:@Select注解中加入字段判断
【mybatis】第二篇:@Select注解中加入字段判断
|
2天前
|
Java Spring 容器
SpringBoot自动装配原理之@Import注解解析
SpringBoot自动装配原理之@Import注解解析
|
2天前
|
存储 缓存 NoSQL
Springboot中使用redisson + 自定义注解优雅的实现消息的发布订阅
Springboot中使用redisson + 自定义注解优雅的实现消息的发布订阅
|
5天前
|
XML Java 数据库连接
Javaweb之Mybatis的XML配置文件的详细解析
Javaweb之Mybatis的XML配置文件的详细解析
13 0
|
15天前
|
XML Java API
springboot 常用的注解标签的概念及用法RequiredArgsConstructor 、RestController、RequestMapping
【4月更文挑战第12天】在 Spring Boot 中,@RequiredArgsConstructor, @RestController, 和 @RequestMapping 是常用的注解,每个都有其特定的功能和用法,它们合起来极大地简化了 Spring 应用程序的开发过程。
20 2
|
18天前
|
存储 关系型数据库 MySQL
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
|
19天前
|
Java 容器
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
15 0
|
30天前
|
Java 数据库连接 mybatis
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
19 0