这两天自己在捣鼓SpringBoot和Mybatis的整合,由于自己有点水,搞了一天才真正搞定,现在将自己在路上遇到的坑记录下,以后尽量避免。
一、数据准备
首先在mysql数据库中创建数据库和表,并且插入一些数据。
create database if not exists mybatis;
use mybatis;
drop table if exists t_pipeline;
create table if not exists t_pipeline
(
pipelineId varchar(64) primary key,
pipelineName varchar(32) not null,
currentUser varchar(32) not null
);
insert into t_pipeline
value
(
replace(uuid(), "-", ""),
'pipelineTest001',
'lordstar'
),
(
replace(uuid(), "-", ""),
'pipelineTest002',
'xiaowang'
),
(
replace(uuid(), "-", ""),
'pipelineTest003',
'xiaoming'
),
(
replace(uuid(), "-", ""),
'pipelineTest004',
'xiaoli'
)
二、直接创建在官网上创建SpringBoot项目。
三、数据库配置文件
在resource下面创建application.yml文件,具体配置如下:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis
username: root
data-password: root
四、按照框架配置mybatis
首先项目的相关文件结构如图:
接下来对么个文件进行说明
1、DataBaseConfiguration
这个文件中主要是对数据库进行初始化的,代码中的DataSource用了Tomcat的,由于只是初始版,事务也没有加进去,后面会进行补充
package org.lordstar.studentmanage.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@MapperScan("org.lordstar.studentmanage.dao")
public class DataBaseConfiguration {
@Value("${spring.datasource.driver-class-name}")
private String driveClass;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.data-password}")
private String password;
@Bean(name="dataSource")
public DataSource dataSource() {
DataSource dataSource = new DataSource();
dataSource.setDriverClassName(driveClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("org.lordstar.studentmanage.model");
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
MapperScan注解加上之后才会扫描该包下面的mapper类,才会在上下文中产生该Dao对象。
2、IPipelineDao和model
package org.lordstar.studentmanage.dao;
import java.util.List;
import org.lordstar.studentmanage.model.Pipeline;
public interface IPipelineDao {
public List<Pipeline> findAllPipeline();
}
Pipeline的model
package org.lordstar.studentmanage.model;
import org.apache.ibatis.type.Alias;
@Alias("pipeline")
public class Pipeline {
private String pipelineId;
private String pipelineName;
private String user;
public String getPipelineId() {
return pipelineId;
}
public void setPipelineId(String pipelineId) {
this.pipelineId = pipelineId;
}
public String getPipelineName() {
return pipelineName;
}
public void setPipelineName(String pipelineName) {
this.pipelineName = pipelineName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
这里给Pipeline指定了别名,这个在后面的xml文件中就不用再用全包名路径来表示这个model了
3、映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lordstar.studentmanage.dao.IPipelineDao">
<resultMap type="pipeline" id="pipelineMap">
<id property="pipelineId" column="pipelineId" javaType="java.lang.String"></id>
<result property="pipelineName" column="pipelineName" javaType="java.lang.String"></result>
<result property="user" column="currentUser" javaType="java.lang.String"></result>
</resultMap>
<select id="findAllPipeline" resultMap="pipelineMap">
select * from t_pipeline
</select>
</mapper>
这里自定义了resultMap,方便sql语句的返回和对象映射起来。
4、controller
按照上面的配置和代码之后,基本的功能就已经实现了,接下来就是编写controller进行使用了
package org.lordstar.studentmanage.controller;
import java.util.List;
import org.lordstar.studentmanage.dao.IPipelineDao;
import org.lordstar.studentmanage.model.Pipeline;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/pipeline")
public class PipelineController {
@Autowired
private IPipelineDao pipelineDao;
@GetMapping("/getpipelines")
public List<Pipeline> getAllPipelines() {
return pipelineDao.findAllPipeline();
}
}