【SpringBoot实战】之整合mybatis

star2017 1月前 ⋅ 57 阅读

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);
  }

}

源码地址

本文为博主原创文章,未经博主允许不得转载。
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: