Springboot整合mybatis

使用springboot整合mybatis。使用代码配置。

整体结构:

1. 添加所需依赖

<?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.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>

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

</project>

 

2. 先在application.properties里面配置数据库信息

database.jdbc-url = jdbc:mysql://localhost:3306/common?characterEncoding=utf-8
database.username = root
database.password = root
database.driverClassName =com.mysql.jdbc.Driver

3. 新建配置类Config,配置数据库信息,并且指定mapper的路径

@Configuration
public class Config {
    @Bean
    @ConfigurationProperties(prefix = "database")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactoryBean")
    public static SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);

        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.demo.vo");
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*Mapper.xml"));

        //设置值为null时的 jdbcType
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);

        return sqlSessionFactory;
    }

    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        mapperScannerConfigurer.setBasePackage("com.example.demo.mapper");
        return mapperScannerConfigurer;
    }

}

4. 创建业务处理层。

public interface UserService {
    String insert(User user);
    String delete(int id);
}
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public String insert(User user) {
        userMapper.insert(user);
        return "OK";
    }

    @Override
    public String delete(int id) {
        userMapper.delete(id);
        return "OK";
    }
}

5. 创建mapper

@Repository
public interface UserMapper  {
    void insert(User user);
    void delete(int 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.example.demo.mapper.UserMapper">

    <insert id="insert">
         insert into USer (id,name,age) values (#{id},#{name},#{age});
    </insert>

    <delete id="delete">
          delete  from USer where id = #{id}
    </delete>

</mapper>

注意namespace,要映射到上面的UserMapper接口

6. 创建BaseController 和 ResultResonse,来创建标准化的返回值接口。

package com.example.demo.response;

public class ResultResponse<T> {
    private T data;
    private int code;
    private String errorMsg;

    public int getCode() {
        return code;
    }

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

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
package com.example.demo.controller;

import com.example.demo.response.ResultResponse;

import java.util.List;

public class BaseController<T> {
    protected ResultResponse handleResult(List<T> list){
        ResultResponse resultResponse = new ResultResponse();
        resultResponse.setCode(0);
        resultResponse.setErrorMsg(null);
        resultResponse.setData(list);
        return resultResponse;
    }

    protected ResultResponse handleResult(String list){
        ResultResponse resultResponse = new ResultResponse();
        resultResponse.setCode(0);
        resultResponse.setErrorMsg(null);
        resultResponse.setData(list);
        return resultResponse;
    }
}

7. 创建controller,继承BaseController

package com.example.demo.controller;

import com.example.demo.response.ResultResponse;
import com.example.demo.service.UserService;
import com.example.demo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/test")
public class UserController extends BaseController{

    @Autowired
    UserService userService;

    @RequestMapping(value = "/insertUser",method = RequestMethod.POST)
    public ResultResponse insertUser(User user){
        return handleResult(userService.insert(user));
    }


    @RequestMapping("/deleteUser/{id}")
    public ResultResponse deleteUserById(@PathVariable int id){
        return handleResult(userService.delete(id));
    }

}

8. Application启动类没有过多的更改

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

9. 启动运行测试

 over。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值