【SpringBoot 实战】之整合 mybatis

本贴最后更新于 1918 天前,其中的信息可能已经时过境迁

mybatis 框架的好处,这里就不说了,一般你要使用 ORM 框架,都会选择他。

今天来讲讲 SpringBoot 项目里面怎么使用 mybatis。文末有源码地址。

整体结构

imagepng

pom 配置

<?xml version="1.0" encoding="UTF-8"?>
<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>com.cimu</groupId>
	<artifactId>mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
			<version>2.7.8</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

sql 文件

CREATE TABLE `user` (
  `id` BIGINT(64) NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
  `real_name` VARCHAR(100) DEFAULT NULL COMMENT '真实名称',
  `mobile` VARCHAR(11) DEFAULT NULL COMMENT '手机号码',
  `password` VARCHAR(20) DEFAULT NULL COMMENT '密码',
  `create_time` DATETIME DEFAULT NULL COMMENT '创建日期',
  `update_time` DATETIME DEFAULT NULL COMMENT '修改日期',
  `del_flag` CHAR(1) NOT NULL DEFAULT '0' COMMENT '删除标记 1:删除;0:未删除'
)AUTO_INCREMENT=0 COMMENT='用户表';

配置文件

application.properties:

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

#注意:一定要对应mapper映射xml文件的所在路径/src/main/resources下
mybatis.mapper-locations=classpath:mapping/*.xml
# 注意:对应实体类的路径
mybatis.type-aliases-package=com.cimu.mybatis.entity

代码编写

user 类:

public class User {

    /**
	* 主键ID */  
 private Long id;
  /**
 * 真实名称 */  
 private String realName;
  /**
 * 手机号码 */  
 private String mobile;
  /**
 * 密码 */  
 private String password;
  /**
 * 创建日期 */  
 private Date createTime;
  /**
 * 修改日期 */  
 private Date updateTime;
  /**
 * 删除标记 1:删除;0:未删除 */  
 private String delFlag;

 .....省略get/set方法

}

MybatisApplication 类:

@SpringBootApplication
@MapperScan("com.cimu.mybatis.mapper")//将项目中对应的mapper类的路径加进来就可以了
public class MybatisApplication {

   public static void main(String[] args) {
      SpringApplication.run(MybatisApplication.class, args);
  }
}

UserService 类:

public interface UserService {

    User getById(Long id);

    List<User> selectAll(String realName);

    void deleteById(Long id);

}

UserServiceImpl 类:

@Service
public class UserServiceImpl implements UserService{
    @Autowired
  private UserMapper userMapper;

  @Override
  public User getById(Long id) {
        return userMapper.getById(id);
  }

    @Override
  public List selectAll(String realName) {
        User user = new User();
  user.setRealName(realName);
 return userMapper.selectAll(user);
  }

    @Override
  public void deleteById(Long id) {
        userMapper.deleteById(id);
  }

}

UserMapper 类:

public interface UserMapper {

  User getById(Long id);

  List selectAll(User user);

 int deleteById(Long id);

}

UserMapper.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="com.cimu.mybatis.mapper.UserMapper">


    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, real_name as realName, mobile, password, create_time as createTime,
        update_time as updateTime, del_flag as delFlag
    </sql>

    <select id="getById" resultType="com.cimu.mybatis.entity.User">
        select <include refid="Base_Column_List"/>
        from user where id=#{id}
    </select>

    <select id="selectAll" resultType="com.cimu.mybatis.entity.User" parameterType="com.cimu.mybatis.entity.User">
        select <include refid="Base_Column_List"/>
        from user
        where 1=1
        <if test="realName != null">
            and real_name=#{realName}
        </if>
    </select>

    <delete id="deleteById">
        delete from user where id=#{id}
    </delete>
</mapper>

写了个单元测试类,来测试 service 的方法

package com.cimu.mybatis;

import com.cimu.mybatis.entity.User;
import com.cimu.mybatis.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {
   @Autowired
  private UserService userService;

  @Test
  public void getById() {
      User user = userService.getById(1L);
  System.out.println("realName="+user.getRealName());
  }

    @Test
  public void selectAll() {
        List userList = userService.selectAll("2");
 for(User user : userList){
            System.out.println("realName="+user.getRealName());
  }
    }

    @Test
  public void deleteById() {
        userService.deleteById(1L);
  }

}

源码地址

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1090 引用 • 3467 回帖 • 298 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    938 引用 • 1456 回帖 • 163 关注
  • MyBatis

    MyBatis 本是 Apache 软件基金会 的一个开源项目 iBatis,2010 年这个项目由 Apache 软件基金会迁移到了 google code,并且改名为 MyBatis ,2013 年 11 月再次迁移到了 GitHub。

    170 引用 • 414 回帖 • 430 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
chaigx
欢迎关注我的公众号:程序之声。有些文章没办法同步过来,访问个人博客:http://www.chaiguanxin.com 杭州