您的位置:首页 > 编程语言 > Java开发

springboot整合mybatis

2017-11-17 15:39 435 查看
开发环境eclipse,java 1.8。eclipse已经配置好spring boot,mvn等各种插件
一、新建spring boot项目
new project -> Spring Boot -> Spring Starter Project



填写项目的基本信息



选择使用的组件 MyBatis 和Web 。点击Finish完成新建项目



打开pom.xml 添加Mysql链接驱动,这里用了5.x版本的驱动包
<!-- mysql 连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>


二、配置数据库连接信息。
在application.properties 文件中添加以下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=wzy123456
spring.datasource.max-active=20
spring.datasource.max-idle=20
spring.datasource.min-idle=1

以上配置仅供参考,毕竟我也是从其他地方拷来的。

三、配置数据源

打开spring boot的启动类 SpringbootMybatisApplication.java,添加以下代码:

@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}

spring boot 会根据第二步的数据库配置自动加载数据源

四、配置Mybatis的sqlSessionFactoryBean
数据源配置完成后要配置Mybatis的sqlSessionFactoryBean进行扫描mapper文件。SpringbootMybatisApplication.java,添加以下代码:
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/wzy/db/mapper/*.xml"));

return sqlSessionFactoryBean.getObject();
}

在此,我把mapper文件都放在了 com.wzy.db.mapper包下边

五、配置@MapperScan扫描dao层
这个只需要在SpringbootMybatisApplication.java类上边添加一个注解就可以了,如下图所示:



在这里,我把dao类文件都放在了com.wzy.db.mapper包下边

六、开启数据库事务
还是在SpringbootMybatisApplication.java类中添加以下代码:
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}


七、根据数据库表生成 dao、mapper、model 文件
使用mybatis generator一键生成这三种文件,如果没有安装此插件需要先安装此插件



我数据库中只有一个person表,generatorConfig.xml 的配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<classPathEntry location="E:\Program Files\apache-maven-3.0.5\repos\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />

<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
<property name="searchString" value="Example$" />
<property name="replaceString" value="Criteria" />
</plugin>
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>

<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="wzy123456">
</jdbcConnection>

<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<javaModelGenerator targetPackage="com.wzy.db.model"
targetProject="springboot_mybatis">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>

<sqlMapGenerator targetPackage="com.wzy.db.mapper"
targetProject="springboot_mybatis">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<javaClientGenerator type="XMLMAPPER" targetPackage="com.wzy.db.dao"
targetProject="springboot_mybatis">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>

<table schema="test" tableName="person" domainObjectName="Person"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>

</context>
</generatorConfiguration>


八、编写service和controller

PsersonService.java
package com.wzy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wzy.db.dao.PersonMapper;
import com.wzy.db.model.Person;

@Service
public class PersonService {

@Autowired
PersonMapper personMapper;

public Person getById(Integer id) {
Person p = personMapper.selectByPrimaryKey(id);
return p;
}

}

一定要加上@Service注解

PersonController.java
package com.wzy.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wzy.db.model.Person;
import com.wzy.service.PersonService;

@Controller
@RequestMapping("person")
public class PersonController {

@Autowired
PersonService personService;

@ResponseBody
@RequestMapping("get")
public Object getById(HttpServletRequest request) {
String Id = request.getParameter("id");

Person p = personService.getById(Integer.parseInt(Id));
return p;
}
}

Run As -> Spring Boot App 默认8080端口,浏览器中输入http://localhost:8080/person/get?id=1
可以看到:



spring boot 整合mybaits完毕!
git 地址 https://gitee.com/wangziying/springboot/tree/master/springboot_mybatis 开发技巧:
在pom.xml中添加devtolls,修改任何代码或配置可以自动重新启动,不需要手动启动
<!-- 热部署开发工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: