springboot整合mybatis

本文详细介绍了如何在SpringBoot项目中使用注解配置MyBatis,包括设置目录结构、导入依赖、数据库配置、日志配置,以及如何配置数据源、SqlSessionFactoryBean和自动扫描映射类。还涵盖了创建实体、映射和服务类的步骤以及SQL测试。
摘要由CSDN通过智能技术生成

项目配置

1. 目录结构

在这里插入图片描述

2.导入依赖

        <!-- spring事务依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>6.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.11</version>
        </dependency>

        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>

        <!-- mybatis和spring集成的依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.2</version>
        </dependency>

        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>

        <!-- 阿里公司的数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.18</version>
        </dependency>

        <!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

3. 创建jdbc.properties数据库配置文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

4.创建log4j.properties日志文件

#
log4j.rootLogger=DEBUG,stdout
# MyBatis logging configuration...
# MyBatis
log4j.logger.com.example.test.datasource.service.UserServiceImpl=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

5.创建数据库

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL DEFAULT '',
  `sex` varchar(10) NOT NULL DEFAULT '',
  `birthday` date DEFAULT NULL,
  `address` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

二、配置mybatis自动注入

1.添加主注解

@SpringBootApplication
@MapperScan("com.example.test.datasource.mappers") // 让MyBatis自动扫描指定包的所有Mapper并创建实现类,和下面createMapperScannerConfigurer方法相同作用,两者用其一
@PropertySource("/jdbc.properties")

2.添加数据源

这里使用阿里数据源

    /**
     * 创建数据源
     */
    @Bean
    public DruidDataSource createDataSource(@Value("${jdbc.driver}") String driver, @Value("${jdbc.url}") String url, @Value("${jdbc.username}") String username, @Value("${jdbc.password}") String password)
    {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

3.创建SqlSessionFactoryBean

    /**
     * 创建 SqlSessionFactoryBean
     */
    @Bean
    public SqlSessionFactoryBean createSqlSessionFactoryBean(@Autowired DataSource dataSource, ApplicationContext applicationContext) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 指定数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 指定mybatis主配置文件
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
        // 指定mapper配置文件列表
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mapper_xml/*.xml"));
        return sqlSessionFactoryBean;
    }

4. 创建自动查找映射类并自动注入(方式1)

MapperScannerConfigurer会循环setBasePackage所设置的包,把包中的每个接口都找到,调用SqlSession.getMapper(XXXMapper.class)把每个mapper接口都创建出对应的mapper代理对象,并将mapper代理对象放在容器中。

    /**
     * 和 @MapperScan("com.example.test.datasource.mappers") 相同作用,两者用其一
     */
    @Bean
    public MapperScannerConfigurer createMapperScannerConfigurer()
    {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.example.test.datasource.mappers");
        return configurer;
    }

4. 创建自动查找映射类并自动注入(方式2)

通过给主类配置@MapperScan注释,并指名包路径。多个不同包路径使用{“包1”, “包2”}设置,@MapperScan({“com.example.test.datasource.mappers”, “com.example.test.datasource.mappers2”})

@MapperScan("com.example.test.datasource.mappers") // 让MyBatis自动扫描指定包的所有Mapper并创建实现类,和createMapperScannerConfigurer方法相同作用,两者用其一

三、创建实体、映射、服务类

1.创建实体类

package com.example.test.datasource.entities;

public class User {
    private Long id;

    private String name;

    private String sex;

    private String birthday;

    private String address;

    public User(){}

    public User(String name, String sex, String birthday, String address) {
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
        this.address = address;
    }

    public User(Long id, String name, String sex, String birthday, String address) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
        this.address = address;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

2.创建映射类

package com.example.test.datasource.mappers;

import com.example.test.datasource.entities.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface UserMapper {

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

    /**
     * 使用注解传递多个参数
     */
    @Select("select ${fields} from user where id = #{id}")
    User queryById(@Param("id") int id, @Param("fields") String fields);

    int insertUser(User user);

    int updateUser(User user, User userCondition);

    int deleteById(int id);

    List<User> queryAllByIds(Integer[] ids);

    List<User> queryAllByIdsList(List<Integer> idlist);

    List<User> queryAllByIdsMap(Map<String, Object> idsMap);
}

3.创建服务类

package com.example.test.datasource.service;

import com.example.test.datasource.entities.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserService {

    List<User> queryAll();

    User queryById(int id, String fields);

    int insertUser(User user);

    int updateUser(User user, User userCondition);

    int deleteById(int id);

    List<User> queryAllByIds(Integer[] ids);

    List<User> queryAllByIdsList(List<Integer> idlist);

    List<User> queryAllByIdsMap(Map<String, Object> idsMap);
}

package com.example.test.datasource.service;

import com.example.test.datasource.entities.User;
import com.example.test.datasource.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    UserMapper userMapper;

    public UserServiceImpl(@Autowired UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> queryAll() {
        return userMapper.queryAll();
    }

    @Override
    public User queryById(int id, String fields) {
        return userMapper.queryById(id, fields);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public int updateUser(User user, User userCondition) {
        return userMapper.updateUser(user, userCondition);
    }

    @Override
    public int deleteById(int id) {
        return userMapper.deleteById(id);
    }

    @Override
    public List<User> queryAllByIds(Integer[] ids) {
        return userMapper.queryAllByIds(ids);
    }

    @Override
    public List<User> queryAllByIdsList(List<Integer> idlist) {
        return userMapper.queryAllByIdsList(idlist);
    }

    @Override
    public List<User> queryAllByIdsMap(Map<String, Object> idsMap) {
        return userMapper.queryAllByIdsMap(idsMap);
    }
}

4.SQL测试

        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        List<User> users = userService.queryAll();

运行结果:
在这里插入图片描述

5.完整代码

package com.example.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.test.datasource.entities.User;
import com.example.test.datasource.service.UserServiceImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.*;

@SpringBootApplication
@MapperScan("com.example.test.datasource.mappers") // 让MyBatis自动扫描指定包的所有Mapper并创建实现类,和下面createMapperScannerConfigurer方法相同作用,两者用其一
@PropertySource("/jdbc.properties")
public class TestApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(TestApplication.class, args);
        UserServiceImpl userService = context.getBean(UserServiceImpl.class);
        List<User> users = userService.queryAll();

    }

    /**
     * 创建数据源
     */
    @Bean
    public DruidDataSource createDataSource(@Value("${jdbc.driver}") String driver, @Value("${jdbc.url}") String url, @Value("${jdbc.username}") String username, @Value("${jdbc.password}") String password)
    {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 创建 SqlSessionFactoryBean
     */
    @Bean
    public SqlSessionFactoryBean createSqlSessionFactoryBean(@Autowired DataSource dataSource, ApplicationContext applicationContext) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 指定数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 指定mybatis主配置文件
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
        // 指定mapper配置文件列表
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mapper_xml/*.xml"));
        return sqlSessionFactoryBean;
    }

    /**
     * 和 @MapperScan("com.example.test.datasource.mappers") 相同作用,两者用其一
     */
//    @Bean
//    public MapperScannerConfigurer createMapperScannerConfigurer()
//    {
//        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
//        configurer.setBasePackage("com.example.test.datasource.mappers");
//        return configurer;
//    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值