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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 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方式需要在主启动函数或配置类中配置接口的扫描路径


相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
11天前
|
存储 Java 数据库连接
Mybatisplus中的主要使用注解
3.有些注解需要配合其他配置使用。例如,@Version需要配合乐观锁插件使用,@EnumValue需要配合对应的TypeHandler使用。
60 11
|
1月前
|
SQL XML Java
MyBatis——选择混合模式还是全注解模式?
在MyBatis开发中,Mapper接口的实现方式有两种:全注解模式和混合模式。全注解模式直接将SQL嵌入代码,适合小规模、简单逻辑项目,优点是直观简洁,但复杂查询时代码臃肿、扩展性差。混合模式采用接口+XML配置分离的方式,适合大规模、复杂查询场景,具备更高灵活性与可维护性,但学习成本较高且调试不便。根据项目需求与团队协作情况选择合适模式至关重要。
46 4
|
2月前
|
JSON 前端开发 Java
Spring MVC常用的注解
@RequestMapping:用于处理请求 url 映射的注解,可用于类或方法上。用于类上,则表示类中 的所有响应请求的方法都是以该地址作为父路径。 @RequestBody:注解实现接收http请求的json数据,将json转换为java对象。 @ResponseBody:注解实现将conreoller方法返回对象转化为json对象响应给客户。 @Controller:控制器的注解,表示是表现层,不能用用别的注解代替 @RestController : 组合注解 @Conntroller + @ResponseBody @GetMapping , @PostMapping , @Put
|
2月前
|
Java Spring
Spring Boot的核心注解是哪个?他由哪几个注解组成的?
Spring Boot的核心注解是@SpringBootApplication , 他由几个注解组成 : ● @SpringBootConfiguration: 组合了- @Configuration注解,实现配置文件的功能; ● @EnableAutoConfiguration:打开自动配置的功能,也可以关闭某个自动配置的选项 ● @ComponentScan:Spring组件扫描
|
1月前
|
人工智能 缓存 自然语言处理
保姆级Spring AI 注解式开发教程,你肯定想不到还能这么玩!
这是一份详尽的 Spring AI 注解式开发教程,涵盖从环境配置到高级功能的全流程。Spring AI 是 Spring 框架中的一个模块,支持 NLP、CV 等 AI 任务。通过注解(如自定义 `@AiPrompt`)与 AOP 切面技术,简化了 AI 服务集成,实现业务逻辑与 AI 基础设施解耦。教程包含创建项目、配置文件、流式响应处理、缓存优化及多任务并行执行等内容,助你快速构建高效、可维护的 AI 应用。
|
2月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
55 0
|
4月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
174 2
|
7月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
296 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
7月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
195 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
7月前
|
前端开发 Java Apache
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
本文详细讲解了如何整合Apache Shiro与Spring Boot项目,包括数据库准备、项目配置、实体类、Mapper、Service、Controller的创建和配置,以及Shiro的配置和使用。
1611 1
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个