欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis整合SpringBoot(注解和配置形式)详细操作

程序员文章站 2024-01-26 12:44:58
...

Mybatis整合SpringBoot的两种形式(注解和配置形式)


1.注解形式

1.1 项目用到的相关依赖
Pom.xml如下

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.piggy</groupId>
	<artifactId>springzzz</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springzzz</name>
	<description>Demo project for Spring Boot</description>
	 <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.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
		 	<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

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

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.17</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

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

</project>

1.2 配置文件application.properties

spring.datasource.url= jdbc:mysql://localhost:3306/database1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.login-timeout=1000
spring.datasource.hikari.maximum-pool-size=30

1.3按照数据库的表创建pojo实体类

Mybatis整合SpringBoot(注解和配置形式)详细操作

PS 注解 形式是没有mapper.xml文件的

1.4 创建mapper接口

package com.piggy.mapper;

import com.piggy.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;


//这里可以使用@Repository也可以使用@Mapper注解

@Mapper
public interface UserMapper {

    @Select("select * from user")
    List<User> findAllUser();

}

1.5 响应请求状态的实体类ResultObjec

package com.piggy.pojo;

import java.io.Serializable;

public class ResultObject implements Serializable{
//  响应状态码
    private Integer code;
//  响应信息
    private String message;
//  用来传递对象的属性
    private Object object;

    public ResultObject() {
    }

    public ResultObject(Integer code, String message, Object object) {
        this.code = code;
        this.message = message;
        this.object = object;
    }

    public ResultObject(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public Object getObject() {
        return object;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    @Override
    public String toString() {
        return "ResultObject{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", object=" + object +
                '}';
    }
}

1.6 创建Service接口和实现类

package com.piggy.service;

import com.piggy.pojo.ResultObject;

public interface UserService {

//   返回值是Result
     ResultObject findAll();
}

Service实现类

package com.piggy.service.serviceImpl;

import com.piggy.mapper.UserMapper;
import com.piggy.pojo.ResultObject;
import com.piggy.pojo.User;
import com.piggy.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public ResultObject findAllUser() {
        List<User> userList = userMapper.findAllUser();
        if(userList.size()==0){
//      查询失败
            return new ResultObject(201,"查询失败");
        }else{
            return new ResultObject(200,"查询成功",userList);
        }
    }
}


1.7 编写Controller

package com.piggy.controller;

import com.piggy.pojo.ResultObject;
import com.piggy.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/findAllUser.action")
    public ResultObject findAllUser(){
        return userService.findAllUser();
    }
}

1.8 SpringBoot启动类

package com.piggy.demo;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.piggy")
@MapperScan("com.piggy.mapper")
public class DemoApplication {

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

}

1.9 测试
Mybatis整合SpringBoot(注解和配置形式)详细操作

2.配置文件形式

配置文件形式需要mapper.xml文件,所以需要在application.properties中配置mapper.xml文件的位置

2.1 在application.properties文件中添加
mybatis.mapper-location= classpath:mapping/*.Mapper.xml

Mybatis整合SpringBoot(注解和配置形式)详细操作

2.2 创建mapper.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.piggy.mapper.UserMapper">

    <insert id="addUser" parameterMap="com.piggy.pojo.User">
          INSERT INTO USER (d_name,d_age,d_sex) VALUES (#{d_name}, #{d_age},#{d_sex})
    </insert>
</mapper>

2.3 编写Mapper接口
Mybatis整合SpringBoot(注解和配置形式)详细操作

2.4 编写Service接口和实现类
UserService接口增加的方法
Mybatis整合SpringBoot(注解和配置形式)详细操作

UserServiceImpl增加的方法
Mybatis整合SpringBoot(注解和配置形式)详细操作

2.5 编写UserController
Mybatis整合SpringBoot(注解和配置形式)详细操作

2.6 启动测试

Mybatis整合SpringBoot(注解和配置形式)详细操作