SpringBoot之整合Mybatis
2018-03-27 14:49
471 查看
1.添加数据库及相关数据库表(此处数据库为mysql)
4.src/main/resources下添加application.properties文件【用于添加数据库相关配置信息】
5.编写mybatis的配置类,dao层,service层MybatisMapperScanConfig.java
package com.caixing.learn.springboot.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jasypt.util.text.BasicTextEncryptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
/**
*
* <Description> 添加mybatis的mapper配置信息 <br>
* @author caixing<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年3月27日 <br>
*/
@ConfigurationProperties
public class MybatisConfig {
/**
* 注入环境变量的值
*/
@Autowired
private Environment environment;
private BasicTextEncryptor stringEncryptor = new BasicTextEncryptor();
@Bean("druidDataSource")
public DataSource duridDataSource() {
// 获取加密参数
stringEncryptor.setPassword(environment.getProperty("jasypt.encryptor.password"));
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
String encoderUserName = environment.getProperty("spring.datasource.username");
druidDataSource.setUsername(stringEncryptor.decrypt(encoderUserName));
String encoderPass = environment.getProperty("spring.datasource.password");
druidDataSource.setPassword(stringEncryptor.decrypt(encoderPass));
druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
druidDataSource.setMaxActive(Integer.parseInt(environment.getProperty("spring.datasource.maxActive")));
druidDataSource.setInitialSize(Integer.parseInt(environment.getProperty("spring.datasource.initialSize")));
druidDataSource.setMaxWait(Long.parseLong(environment.getProperty("spring.datasource.maxWait")));
druidDataSource.setMinIdle(Integer.parseInt(environment.getProperty("spring.datasource.minIdle")));
druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(environment.getProperty("spring.datasource.poolPreparedStatements")));
druidDataSource.setMaxOpenPreparedStatements(Integer.parseInt(environment.getProperty("spring.datasource.maxOpenPreparedStatements")));
return druidDataSource;
}
/**
* 获取SqlSessionFactory
*
* @param druidDataSource
* @return
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource druidDataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(druidDataSource);
bean.setTypeAliasesPackage(environment.getProperty("mybatis.type-aliases-package"));
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String xmlPath = environment.getProperty("mybatis.mapperLocations");
try {
bean.setMapperLocations(resolver.getResources(xmlPath));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 增加事务
*
* @param druidDataSource
* @return
*/
@Bean
public DataSourceTransactionManager transactionManager(DataSource druidDataSource) {
return new DataSourceTransactionManager(druidDataSource);
}
}
启动mybatis插件,自动生成entity、mapper、mapper.xml(命令为:mybatis-generator:generate)6.测试配置是否成功UserService.java
package com.caixing.learn.springboot.service.impl;
import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.mapper.UserMapper;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper mapper;
@Override
public int createUser(User user) {
int num =mapper.insert(user);
return num;
}
}
HelloController.java
package com.caixing.learn.springboot.controller;
import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class HelloController {
@Autowired
private UserService service;
@GetMapping("/create")
@ResponseBody
public String createUser() {
String msg = "添加成功";
User user = new User();
user.setName("caixing");
try {
int num = service.createUser(user);
if (num < 1) {
msg = "添加失败";
}
} catch (Exception e) {
msg = "添加失败";
}
return msg;
}
}
App.java
package com.caixing.learn.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}启动,并在浏览器访问:http://127.0.0.1:9090/user/create
7.本示例的GitHub地址https://github.com/caixingjava/springboot_mybatis
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;2.新建maven工程并在pom.xml中添加相关依赖jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.caixing.learn.springboot</groupId> <artifactId>springboot_mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot_mybatis</name> <url>http://maven.apache.org</url> <!-- 添加SpringBoot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <properties> <!-- 通用配置 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!-- 数据库相关配置版本 --> <druid.version>1.1.9</druid.version> <mybatis.version>1.3.1</mybatis.version> <!-- 数据库链接加密工具类版本 --> <jasypt-spring-boot-starter.version>2.0.0</jasypt-spring-boot-starter.version> <!-- MyBatis-Generator版本 --> <mybatis-generator-core.version>1.3.5</mybatis-generator-core.version> <mybatis-generator-maven-plugin.version>1.3.5</mybatis-generator-maven-plugin.version> <mapper.version>3.4.3</mapper.version> <!-- Java接口和实体类 --> <targetJavaProject>${basedir}/src/main/java</targetJavaProject> <targetMapperPackage>com.caixing.learn.springboot.mapper</targetMapperPackage> <targetModelPackage>com.caixing.learn.springboot.entity</targetModelPackage> <!-- XML生成路径 --> <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject> <targetXMLPackage>mapper</targetXMLPackage> </properties> <dependencies> <!-- 添加WEB --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- 添加mysql数据库插件 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 添加druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- 添加mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <!-- 数据库加密工具类 --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>${jasypt-spring-boot-starter.version}</version> </dependency> <!-- 添加Mybatis-Generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactI 156ab d>mybatis-generator-core</artifactId> <version>${mybatis-generator-core.version}</version> <scope>compile</scope> <optional>true</optional> </dependency> <!--集成通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <!-- 建议使用最新版本 --> <version>${mapper.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration> </plugin> <!--mybatis自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mybatis-generator-maven-plugin.version}</version> <configuration> <!-- 是否覆盖 --> <overwrite>true</overwrite> <!--允许移动生成的文件 --> <verbose>true</verbose> <!-- 自动生成的配置,${basedir}表示项目根目录 ,configurationFile默认在resource目录下 --> <!--<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> --> </configuration> <dependencies> <!--mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <!--集成通用mapper依赖 --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mapper.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>3.在src/main/resources下添加generatorConfig.xml【用于自动生成mapper、entity和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> <!-- 引入配置文件 --> <properties resource="config/application-dev.properties" /> <!-- context:生成一组对象的环境 id:必选,上下文id,用于在生成错误时提示 defaultModelType:指定生成对象的样式 1,conditional:类似hierarchical; 2,flat:所有内容(主键,blob)等全部生成在一个对象中; 3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class) targetRuntime: 1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample; 2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample; introspectedColumnImpl:类全限定名,用于扩展MBG --> <context id="Mysql" targetRuntime="MyBatis3"> <!--https://mapperhelper.github.io/docs/3.usembg/,自动生成代码的通用mapper插件 --> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <property name="mappers" value="tk.mybatis.mapper.common.Mapper" /> <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true --> <!-- <property name="caseSensitive" value="true"/> --> </plugin> <!-- 注释 --> <commentGenerator> <!-- 是否取消自动生成的注释 --> <!--<property name="suppressAllComments" value="true"/> --> <!-- 是否生成注释代时间戳 --> <!--<property name="suppressDate" value="false" /> --> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}"> <!-- 针对mysql数据库 --> <property name="useInformationSchema" value="true" /> </jdbcConnection> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="true" /> </javaTypeResolver> <!-- 生成实体类地址 --> <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <!--<property name="enableSubPackages" value="true" /> --> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <!--<property name="trimStrings" value="true" /> --> </javaModelGenerator> <!-- 生成mapxml文件 --> <sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <!-- <property name="enableSubPackages" value="true" /> --> </sqlMapGenerator> <!-- 生成mapxml对应client,也就是接口dao --> <javaClientGenerator type="XMLMAPPER" targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <!--<property name="enableSubPackages" value="true" /> --> </javaClientGenerator> <table tableName="%" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <columnOverride column="is_display" javaType="Boolean" /> <columnOverride column="content_type" javaType="Integer" /> <columnOverride column="is_deleted" javaType="Boolean" /> <columnOverride column="is_reproduced" javaType="Boolean" /> <columnOverride column="is_finished" javaType="Boolean" /> </table> </context> </generatorConfiguration>
4.src/main/resources下添加application.properties文件【用于添加数据库相关配置信息】
#=========================全局配置============================= #端口 server.port=9090 #=====================mysql的相关配置============================ spring.datasource.url = jdbc:mysql://192.168.2.106:3306/test1?characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver #=====================链接池的相关配置============================= spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.maxActive=20 spring.datasource.initialSize=1 spring.datasource.maxWait=60000 spring.datasource.minIdle=1 spring.datasource.validationQuery=select 1 spring.datasource.poolPreparedStatements=1 spring.datasource.maxOpenPreparedStatements=20 #=====================mybatis的相关配置============================ mybatis.type-aliases-package=com.caixing.learn.springboot.entity mybatis.mapperLocations=classpath:mapper/*.xml
5.编写mybatis的配置类,dao层,service层MybatisMapperScanConfig.java
package com.caixing.learn.springboot.config; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import tk.mybatis.spring.mapper.MapperScannerConfigurer; /** * * <Description> mybatis的扫描配置文件 <br> * @author caixing<br> * @version 1.0<br> * @taskId <br> * @CreateDate 2018年3月27日 <br> */ @Configuration @AutoConfigureAfter(MybatisConfig.class) public class MabatisMapperScanConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("com.caixing.learn.springboot.mapper"); return mapperScannerConfigurer; } }MybatisConfig.java
package com.caixing.learn.springboot.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jasypt.util.text.BasicTextEncryptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
/**
*
* <Description> 添加mybatis的mapper配置信息 <br>
* @author caixing<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年3月27日 <br>
*/
@ConfigurationProperties
public class MybatisConfig {
/**
* 注入环境变量的值
*/
@Autowired
private Environment environment;
private BasicTextEncryptor stringEncryptor = new BasicTextEncryptor();
@Bean("druidDataSource")
public DataSource duridDataSource() {
// 获取加密参数
stringEncryptor.setPassword(environment.getProperty("jasypt.encryptor.password"));
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
String encoderUserName = environment.getProperty("spring.datasource.username");
druidDataSource.setUsername(stringEncryptor.decrypt(encoderUserName));
String encoderPass = environment.getProperty("spring.datasource.password");
druidDataSource.setPassword(stringEncryptor.decrypt(encoderPass));
druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
druidDataSource.setMaxActive(Integer.parseInt(environment.getProperty("spring.datasource.maxActive")));
druidDataSource.setInitialSize(Integer.parseInt(environment.getProperty("spring.datasource.initialSize")));
druidDataSource.setMaxWait(Long.parseLong(environment.getProperty("spring.datasource.maxWait")));
druidDataSource.setMinIdle(Integer.parseInt(environment.getProperty("spring.datasource.minIdle")));
druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(environment.getProperty("spring.datasource.poolPreparedStatements")));
druidDataSource.setMaxOpenPreparedStatements(Integer.parseInt(environment.getProperty("spring.datasource.maxOpenPreparedStatements")));
return druidDataSource;
}
/**
* 获取SqlSessionFactory
*
* @param druidDataSource
* @return
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource druidDataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(druidDataSource);
bean.setTypeAliasesPackage(environment.getProperty("mybatis.type-aliases-package"));
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String xmlPath = environment.getProperty("mybatis.mapperLocations");
try {
bean.setMapperLocations(resolver.getResources(xmlPath));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 增加事务
*
* @param druidDataSource
* @return
*/
@Bean
public DataSourceTransactionManager transactionManager(DataSource druidDataSource) {
return new DataSourceTransactionManager(druidDataSource);
}
}
启动mybatis插件,自动生成entity、mapper、mapper.xml(命令为:mybatis-generator:generate)6.测试配置是否成功UserService.java
package com.caixing.learn.springboot.service; import com.caixing.learn.springboot.entity.User; public interface UserService { public int createUser(User user); }UserServiceImpl.java
package com.caixing.learn.springboot.service.impl;
import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.mapper.UserMapper;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper mapper;
@Override
public int createUser(User user) {
int num =mapper.insert(user);
return num;
}
}
HelloController.java
package com.caixing.learn.springboot.controller;
import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class HelloController {
@Autowired
private UserService service;
@GetMapping("/create")
@ResponseBody
public String createUser() {
String msg = "添加成功";
User user = new User();
user.setName("caixing");
try {
int num = service.createUser(user);
if (num < 1) {
msg = "添加失败";
}
} catch (Exception e) {
msg = "添加失败";
}
return msg;
}
}
App.java
package com.caixing.learn.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}启动,并在浏览器访问:http://127.0.0.1:9090/user/create
7.本示例的GitHub地址https://github.com/caixingjava/springboot_mybatis
相关文章推荐
- springboot(3)整合mybatis
- SpringBoot入门-快速整合Mybatis
- [四]Spring Boot 整合Mybatis
- Spring-boot学习(二):IntelliJ IDEA Spring-boot 整合mybatis
- SpringBoot整合Mybatis提示SAXParseException: 前言中不允许有内容
- SpringBoot学习-(二十)SpringBoot整合Mybatis-plus
- JavaEE开发之SpringBoot整合MyBatis以及Thymeleaf模板引擎
- SpringBoot整合Mybatis使用Druid数据库连接池
- Spring-Boot学习(3)-----Spring-Boot整合mybatis
- Spring Boot+Mybatis的整合过程
- spring boot 整合 mybatis
- Spring boot整合mybatis
- 企业级 SpringBoot 教程 (六)springboot整合mybatis
- SpringBoot+mybatis+gradle的多模块项目整合
- springboot与mybatis整合dao层不能注入的问题
- springboot整合mybatis将sql打印到日志
- spring boot整合mybatis
- springboot 整合mybatis
- 玩转springboot:整合mybatis实例
- spring-boot整合mybatis