SpringBoot整合MyBatis 3.x

本文详细介绍了如何在SpringBoot项目中整合MyBatis框架,包括依赖引入、基础配置、Druid数据源配置、创建数据库表、实体类定义、Mapper接口设计及测试方法。通过具体示例,展示了插入、查询等基本操作。
摘要由CSDN通过智能技术生成

SpringBoot整合MyBatis 3.x

  1. 引入依赖
<!--MyBatis Starter-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
    <scope>runtime</scope>
</dependency>

<!--MySQL JDBC: 数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!--druid:数据源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>
  1. 基础配置
# datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.1.122:3306/avaos?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=weizg
#默认数据源
#spring.datasource.type=com.zaxxer.hikari.HikariDataSource
#引入第三方数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# MyBatis
mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.type-aliases-package=cn.avaos.domain
mybatis.configuration.map-underscore-to-camel-case=true
#打印SQL,用于本地开发测试
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  1. Druid配置
/**
 * Druid连接池配置
 * Author: avaos
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

}
  1. 创建表
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '用户名',
  `phone` varchar(16) COLLATE utf8_bin DEFAULT NULL COMMENT '手机号',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `create_time` date DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  1. 用户
/**
 * Author: avaos
 */
public class User {

    private int id;
    private String name;
    private String phone;
    private Date birthday;
    private Date createTime;

    public User() {
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", birthday=" + birthday +
                ", createTime=" + createTime +
                '}';
    }
}
  1. Mapper
/**
 * 访问并操作数据库
 * Author: avaos
 */
@Mapper
public interface UserMapper {

    /*插入用户*/
    @Insert("insert into user(name, phone, birthday, create_time) values(#{name}, #{phone}, #{birthday}, #{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id") //返回主键
    int insert(User user);

    /*根据ID查询用户信息*/
    @Select("select * from user where id=#{id}")
    User findUserById(Integer id);

    /*查询所有用户信息*/
    @Select("select * from user")
    List<User> findAll();
}
  1. 测试
/**
 * 测试
 * Author: avaos
 */
@SpringBootTest
public class UserMapperTest {

  @Autowired
  private UserMapper userMapper;

  @Test
  public void testInsert() {
    Random random = new Random();
    for(int i=0; i<10;i++) {
      User user = new User();
      user.setName("avaos_" + (random.nextInt(8999) + 1000));
      user.setPhone("1xxxxxx" + (random.nextInt(8999) + 1000));
      user.setBirthday(new Date());
      user.setCreateTime(new Date());
      int rows=userMapper.insert(user);
      System.out.println(String.format("rows:%d", rows));
      System.out.println(String.format("id=%d", user.getId()));
    }
  }

  @Test
  public void testFindUserById() {
    User user = userMapper.findUserById(2);
    System.out.println(user);
  }

  @Test
  public void testFindAll() {
    List<User> list = userMapper.findAll();
    System.out.println(list);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一鹿由妳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值