SpringBoot整合Mybatis

本文介绍了如何在SpringBoot项目中整合Mybatis,通过添加Maven依赖并配置application.yml文件,实现数据访问。核心配置类需放置在顶层包下,以确保生效。通过示例展示了如何访问如http://localhost:8080/user/1的API。
摘要由CSDN通过智能技术生成

mybatis-spring方式

引入Maven依赖

<dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.43</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </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>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP-java7</artifactId>
            <version>2.4.11</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>
    </dependencies>

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF8&useSSL=false
    username: root
    password: root
    basePackage: classpath:mybatis/mapper/*.xml
    driver-class-name: com.mysql.jdbc.Driver
    minIdle: 10
    maxActive: 18
    validationQuery: select 1
    maxWait: 60000

mybati配置

import com.github.pagehelper.PageInterceptor;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan("test.mapper")
@ConfigurationProperties(prefix="spring.datasource")
public class DataSourceConfiguration {
    private String username;
    private String password;
    private String url;
    private String driverClassName;
    private int minIdle;
    private int maxActive;
    private String validationQuery;
    private long maxWait;
    private String basePackage;

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public void setMaxWait(long maxWait) {
        this.maxWait = maxWait;
    }


    @Bean(destroyMethod="close")
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setUsername(username);
        config.setPassword(password);
        config.setJdbcUrl(url);
        config.setMinimumIdle(minIdle);
        config.setDriverClassName(driverClassName);
        config.setMaximumPoolSize(maxActive);
        config.setConnectionTestQuery(validationQuery);
        config.setConnectionTimeout(maxWait);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(basePackage));
        //mybatis的分页插件
        sqlSessionFactoryBean.setPlugins(mybatisPlugins());
        //自定义一些配置
        //sqlSessionFactoryBean.setConfiguration(myConfiguration());
        return sqlSessionFactoryBean.getObject();
    }

    private org.apache.ibatis.session.Configuration myConfiguration() {
        org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();
        //是否启用 数据中 a_column 自动映射 到 java类中驼峰命名的属性。[默认:false]
        conf.setMapUnderscoreToCamelCase(true);
        return conf;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    private Interceptor[] mybatisPlugins() {
        PageInterceptor interceptor = new PageInterceptor();
        Properties pageHelperProps = new Properties();
        pageHelperProps.setProperty("helperDialect", "mysql");
        pageHelperProps.setProperty("offsetAsPageNum", "true");
        pageHelperProps.setProperty("pageSizeZero", "true");
        pageHelperProps.setProperty("rowBoundsWithCount", "true");
        interceptor.setProperties(pageHelperProps);

        Interceptor[] plugins = {interceptor};
        return plugins;
    }
}
启动类Application

注意:该类必须放在顶层包下,我这个是test.**.**,那么这个类就应该放在test包下

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

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

UserController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import test.entity.User;
import test.service.UserService;

@RestController
public class UserController {
    @Autowired
    private UserService service;

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String test(@PathVariable Integer id) {
        User user = service.findUserById(id);
        return user.toString();
    }

}
UserService

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import test.entity.User;
import test.mapper.UserMapper;

@Service
public class UserService {
    @Autowired
    private UserMapper mapper;

    public User findUserById(Integer id) {
        return mapper.findUserById(id);
    }
}
UserMapper

import org.apache.ibatis.annotations.Param;
import test.entity.User;

public interface UserMapper {
    User findUserById(@Param("id") Integer 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="test.mapper.UserMapper">
    <select id="findUserById" resultType="test.entity.User">
        select * from user where id = #{id}
    </select>
</mapper>

Entity

public class User {
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

启动项目

访问http://localhost:8080/user/1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值