mybatis 是一个优秀的持久层框架,支持定制化 sql、存储过程以及高级映射。下面详细介绍如何在 spring boot 项目中整合 mybatis 并连接数据库。
一、基本配置
1. 添加依赖
在pom.xml中添加以下依赖:
<!-- spring boot starter web -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- mybatis spring boot starter -->
<dependency>
<groupid>org.mybatis.spring.boot</groupid>
<artifactid>mybatis-spring-boot-starter</artifactid>
<version>2.2.0</version> <!-- 使用最新版本 -->
</dependency>
<!-- 数据库驱动,根据你的数据库选择 -->
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<scope>runtime</scope>
</dependency>
<!-- 其他可能需要的依赖 -->
<dependency>
<groupid>com.alibaba</groupid>
<artifactid>druid-spring-boot-starter</artifactid>
<version>1.2.6</version> <!-- druid 连接池 -->
</dependency>2. 配置数据库连接
在application.yml或application.properties中配置数据库连接:
# application.yml 配置示例
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database?usessl=false&servertimezone=utc&characterencoding=utf8
username: your_username
password: your_password
driver-class-name: com.mysql.cj.jdbc.driver
type: com.alibaba.druid.pool.druiddatasource # 使用druid连接池
# mybatis 配置
mybatis:
mapper-locations: classpath:mapper/*.xml # mapper.xml文件位置
type-aliases-package: com.example.model # 实体类所在包
configuration:
map-underscore-to-camel-case: true # 开启驼峰命名转换二、项目结构
典型的项目结构如下:
src/main/java
└── com.example.demo
├── demoapplication.java # 启动类
├── config
│ └── mybatisconfig.java # mybatis配置类(可选)
├── controller
│ └── usercontroller.java # 控制器
├── service
│ ├── userservice.java # 服务接口
│ └── impl
│ └── userserviceimpl.java # 服务实现
├── mapper
│ └── usermapper.java # mapper接口
└── model
└── user.java # 实体类
src/main/resources
├── application.yml # 配置文件
└── mapper
└── usermapper.xml # sql映射文件三、核心组件实现(示例)
1. 实体类
package com.example.model;
public class user {
private long id;
private string username;
private string password;
private string email;
// getters and setters
// tostring()
}2. mapper 接口
package com.example.mapper;
import com.example.model.user;
import org.apache.ibatis.annotations.*;
import java.util.list;
@mapper // 重要:标识这是一个mybatis的mapper接口
public interface usermapper {
@select("select * from user where id = #{id}")
user findbyid(long id);
@insert("insert into user(username, password, email) values(#{username}, #{password}, #{email})")
@options(usegeneratedkeys = true, keyproperty = "id")
int insert(user user);
@update("update user set username=#{username}, password=#{password}, email=#{email} where id=#{id}")
int update(user user);
@delete("delete from user where id=#{id}")
int delete(long id);
// xml配置方式
list<user> findall();
}3. mapper xml 文件
src/main/resources/mapper/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.mapper.usermapper">
<resultmap id="userresultmap" type="user">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
</resultmap>
<select id="findall" resultmap="userresultmap">
select * from user
</select>
</mapper>4. service 层
package com.example.service;
import com.example.model.user;
import java.util.list;
public interface userservice {
user findbyid(long id);
list<user> findall();
int save(user user);
int update(user user);
int delete(long id);
}service层实现类:
package com.example.service.impl;
import com.example.mapper.usermapper;
import com.example.model.user;
import com.example.service.userservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import java.util.list;
@service
public class userserviceimpl implements userservice {
@autowired
private usermapper usermapper;
@override
public user findbyid(long id) {
return usermapper.findbyid(id);
}
@override
public list<user> findall() {
return usermapper.findall();
}
@override
public int save(user user) {
return usermapper.insert(user);
}
@override
public int update(user user) {
return usermapper.update(user);
}
@override
public int delete(long id) {
return usermapper.delete(id);
}
}5. controller 层:
package com.example.controller;
import com.example.model.user;
import com.example.service.userservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import java.util.list;
@restcontroller
@requestmapping("/users")
public class usercontroller {
@autowired
private userservice userservice;
@getmapping("/{id}")
public user getuser(@pathvariable long id) {
return userservice.findbyid(id);
}
@getmapping
public list<user> getallusers() {
return userservice.findall();
}
@postmapping
public int createuser(@requestbody user user) {
return userservice.save(user);
}
@putmapping
public int updateuser(@requestbody user user) {
return userservice.update(user);
}
@deletemapping("/{id}")
public int deleteuser(@pathvariable long id) {
return userservice.delete(id);
}
}四、高级特性
1. 动态sql
在xml中使用动态sql:
<select id="findbycondition" parametertype="map" resultmap="userresultmap">
select * from user
<where>
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</where>
</select>2. 分页查询
使用pagehelper插件:
添加依赖:
<select id="findbycondition" parametertype="map" resultmap="userresultmap">
select * from user
<where>
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</where>
</select>使用示例:
<dependency>
<groupid>com.github.pagehelper</groupid>
<artifactid>pagehelper-spring-boot-starter</artifactid>
<version>1.4.1</version>
</dependency>3. 多数据源配置
配置多个数据源:
spring:
datasource:
primary:
url: jdbc:mysql://localhost:3306/db1
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.driver
secondary:
url: jdbc:mysql://localhost:3306/db2
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.driver创建配置类:
@configuration
@mapperscan(basepackages = "com.example.mapper.primary", sqlsessionfactoryref = "primarysqlsessionfactory")
public class primarydatasourceconfig {
@bean(name = "primarydatasource")
@configurationproperties(prefix = "spring.datasource.primary")
public datasource primarydatasource() {
return datasourcebuilder.create().build();
}
@bean(name = "primarysqlsessionfactory")
public sqlsessionfactory primarysqlsessionfactory(@qualifier("primarydatasource") datasource datasource) throws exception {
sqlsessionfactorybean bean = new sqlsessionfactorybean();
bean.setdatasource(datasource);
bean.setmapperlocations(new pathmatchingresourcepatternresolver().getresources("classpath:mapper/primary/*.xml"));
return bean.getobject();
}
@bean(name = "primarytransactionmanager")
public datasourcetransactionmanager primarytransactionmanager(@qualifier("primarydatasource") datasource datasource) {
return new datasourcetransactionmanager(datasource);
}
}
// 类似地创建secondarydatasourceconfig五、常见问题解决
mapper接口无法注入:
- 确保启动类上有
@mapperscan("com.example.mapper")注解 - 或者每个mapper接口上有
@mapper注解
xml文件找不到:
- 检查
mybatis.mapper-locations配置是否正确 - 确保xml文件在resources目录下正确位置
驼峰命名不生效:
- 确认配置
mybatis.configuration.map-underscore-to-camel-case=true
连接池配置:
- 推荐使用druid连接池,并配置合理的连接参数
事务管理:
- 在service方法上添加
@transactional注解
到此这篇关于spring boot 整合 mybatis 连接数据库及常见问题的文章就介绍到这了,更多相关spring boot mybatis 连接数据库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论