【SpringBoot探索五】SpringBoot项目集成Mybatis框架

Mybatis是一个非常流行的Java持久层框架,SpringBoot集成其也非常容易

一.集成mybatis

1.在pom文件中添加依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
    <!--Mybatis for spring boot-->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.0</version>
</dependency>
<!-- mysql -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>

2.在配置文件中配置数据库连接信息

spring:
  datasource:
    url: jdbc:mysql://xxxx:3306/web_app?useUnicode=true&characterEncoding=UTF-8
    username: root #用户名
    password: 12345678 #密码
    driver-class-userName: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml  #指定mapper.xml文件的位置
  type-aliases-package: com.my.webapp.dao.entity #指定映射的实体类位置

3.编写实体类,mapper类,mapper.xml文件

创建一个简单的表t_wa_user,拥有3个字段id, user_name, password

create table t_wa_user(id bigint not null auto_increment primary key, user_name varchar(45) not null COMMENT '用户名',
 password varchar(45) not null COMMENT '密码')ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

编写实体类
User.java

package com.my.webapp.dao.entity;

/**
 */
public class User {

    private Long id;
    /**
     * 用户名
     */
    private String userName;
    /**
     * 密码
     */
    private String password;

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

编写Mapper类,添加一个插入方法insertOne()
UserMapper.java

package com.my.webapp.dao.mapper;

import com.my.webapp.dao.entity.User;
import org.apache.ibatis.annotations.Param;

/**
 */
public interface UserMapper {
    public Integer insertOne(User user);

}

编写该表对应的xml文件
mybatis 编写sql的方式支持xml文件和注解的方式,由于习惯使用xml方式,更方便修改sql以及设计复杂的sql。这里采用的是xml文件的方式。

我这里将xml文件放在resource/mapper目录下,注意配置文件mybatis.mapper-locations属性指定的路径必须是xml文件存放的路径

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.my.webapp.dao.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.my.webapp.dao.entity.User">
        <id column="id" property="id"/>
        <result column="user_name" property="userName"/>
        <result column="password" property="password"/>

    </resultMap>


    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, user_name, password
    </sql>

    <insert id="insertOne">
        INSERT into t_wa_user(user_name, password) VALUES (#{userName}, #{password});
    </insert>

</mapper>

4.在springboot启动类中添加@MapperScan注解

我们还需要配置上对Mapper类的自动扫描,在启动类中加上注解@MapperScan,指定Mapper类的包路径

@MapperScan("com.my.webapp.dao.mapper")

如:
Application.java

package com.my.webapp.app;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 */
@SpringBootApplication
//配置web服务器启动加载指定包下的组件
@ComponentScan(basePackages = {
        "com.my.webapp.app",
        "com.my.webapp.common.config",
        "com.my.webapp.service"
})
@MapperScan("com.my.webapp.dao.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);

    }
}

5.测试insertOne()

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class UserTest {

    @Autowired
    private UserMapper userMapper;
    @Test
    public void insertTest(){
        User user = new User();
        user.setUserName("测试");
        user.setPassword("3243");
        userMapper.insertOne(user);
    }
}

二.配置HikariCp连接池

HikariCp号称性能最好的连接池,可以完美的pk掉其它连接池。项目中同时使用的该连接池

1.添加pom依赖

<dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
</dependency>

2.配置文件添加配置信息

spring:
  datasource:
    url: jdbc:mysql://10.103.7.107:3306/web_app?useUnicode=true&characterEncoding=UTF-8
    username: root #用户名
    password: 12345678 #密码
    driver-class-userName: com.mysql.jdbc.Driver
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      cachePrepStmts: true #设置是否对预编译使用local cache
      prepStmtCacheSize: 250 #指定local cache的大小
      prepStmtCacheSqlLimit: 2048 #长度限制,默认256。超过该长度后,不使用预编译
      #一个连接的生命周期,单位为毫秒,默认30分钟
      max-lifetime: 176500
      #允许的最大连接数,默认10,推荐计算公式 (core_count * 2) + effective_spindle_count
      maximum-pool-size: 15
      #最小空闲连接数
      minIdle: 5

参考案例

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
springboot集成mybatis框架的步骤如下: 1. 首先,在项目的pom.xml文件中添加mybatis的依赖。你可以使用以下的依赖配置来添加mybatis-spring-boot-starter依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> ``` 2. 然后,在springboot的启动类上添加@MapperScan注解,指定mapper接口的包名,让springboot能够扫描到这些接口: ```java @MapperScan(basePackages = "mapper类所放的包名") @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 3. 接下来,需要进行mybatis的配置。在application.properties或application.yml文件中添加mybatis的相关配置: ```yaml # mybatis配置 mybatis: check-config-location: true # 检查mybatis的配置文件位置 config-location: "classpath:mybatis/mybatis-config.xml" # mybatis的配置文件路径 mapper-locations: "classpath:mybatis/mapper/*Mapper.xml" # mapper接口的xml文件路径 type-aliases-package: "com.example.awesomespring.dao.entity.*" # mapper接口对应的实体类路径 ``` 通过以上步骤,你就成功地集成mybatis框架springboot项目中。这样,你就可以使用mybatis来进行数据库的持久化操作了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [手把手教你springboot集成mybatis](https://blog.csdn.net/Trouvailless/article/details/126315399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值