博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis之整合SpringBoot
阅读量:3712 次
发布时间:2019-05-21

本文共 8796 字,大约阅读时间需要 29 分钟。

我们新建一个Mybatis的Maven项目,使用MyBatisGenerator插件自动生成相关的代码

pom.xml

4.0.0
com.yj
MyBatis
0.0.1-SNAPSHOT
jar
MyBatis
http://maven.apache.org
UTF-8
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
com.alibaba
druid-spring-boot-starter
1.1.0
${artifactId}
org.springframework.boot
spring-boot-maven-plugin
true
org.apache.maven.plugins
maven-jar-plugin
com.yj.Application
true
lib
./
config/**
**.xml
**.properties
maven-assembly-plugin
false
src/main/build/package.xml
make-assembly
package
single
src/main/resources

application.properties

server.port=9001spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://192.168.124.129:3306/docker?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=truespring.datasource.username = rootspring.datasource.password = 123456spring.datasource.type= com.alibaba.druid.pool.DruidDataSourcespring.datasource.initialSize= 5spring.datasource.minIdle= 5spring.datasource.maxActive= 20spring.datasource.maxWait= 60000spring.datasource.timeBetweenEvictionRunsMillis= 60000spring.datasource.minEvictableIdleTimeMillis= 300000spring.datasource.validationQuery= SELECT 1 FROM DUALspring.datasource.testWhileIdle= truespring.datasource.testOnBorrow= falsespring.datasource.testOnReturn= falsespring.datasource.poolPreparedStatements= truespring.datasource.maxPoolPreparedStatementPerConnectionSize= 20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters= stat,wall,log4jspring.datasource.connectionProperties= druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #配置mybatismybatis.config-location=classpath:mybatis-config.xmlmybatis.mapper-locations=classpath:mapper/*.xml

mybatis-config.xml

MybatisConfig

package com.yj.config;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Configuration;@Configuration@MapperScan("com.yj.dao")public class MybatisConfig {}

DruidDBConfig

package com.yj.config;import java.sql.SQLException;import javax.sql.DataSource;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import com.alibaba.druid.pool.DruidDataSource;@Configurationpublic class DruidDBConfig {	private Logger log = LoggerFactory.getLogger(this.getClass());	@Value("${spring.datasource.url}")	private String dbUrl;	@Value("${spring.datasource.username}")	private String username;	@Value("${spring.datasource.password}")	private String password;	@Value("${spring.datasource.driverClassName}")	private String driverClassName;	@Value("${spring.datasource.initialSize}")	private int initialSize;	@Value("${spring.datasource.minIdle}")	private int minIdle;	@Value("${spring.datasource.maxActive}")	private int maxActive;	@Value("${spring.datasource.maxWait}")	private int maxWait;	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")	private int timeBetweenEvictionRunsMillis;	@Value("${spring.datasource.minEvictableIdleTimeMillis}")	private int minEvictableIdleTimeMillis;	@Value("${spring.datasource.validationQuery}")	private String validationQuery;	@Value("${spring.datasource.testWhileIdle}")	private boolean testWhileIdle;	@Value("${spring.datasource.testOnBorrow}")	private boolean testOnBorrow;	@Value("${spring.datasource.testOnReturn}")	private boolean testOnReturn;	@Value("${spring.datasource.poolPreparedStatements}")	private boolean poolPreparedStatements;	@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")	private int maxPoolPreparedStatementPerConnectionSize;	@Value("${spring.datasource.filters}")	private String filters;	@Value("${spring.datasource.connectionProperties}")	private String connectionProperties;	@Bean //声明其为Bean实例	@Primary //在同样的DataSource中,首先使用被标注的DataSource	public DataSource dataSource() {		DruidDataSource datasource = new DruidDataSource();		datasource.setUrl(this.dbUrl);		datasource.setUsername(username);		datasource.setPassword(password);		datasource.setDriverClassName(driverClassName);				datasource.setInitialSize(initialSize);		datasource.setMinIdle(minIdle);		datasource.setMaxActive(maxActive);		datasource.setMaxWait(maxWait);		datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);		datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);		datasource.setValidationQuery(validationQuery);		datasource.setTestWhileIdle(testWhileIdle);		datasource.setTestOnBorrow(testOnBorrow);		datasource.setTestOnReturn(testOnReturn);		datasource.setPoolPreparedStatements(poolPreparedStatements);		datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);		try {			datasource.setFilters(filters);		} catch (SQLException e) {			log.error("配置监控统计拦截的filters时发生异常", e);		}		datasource.setConnectionProperties(connectionProperties);		return datasource;	}}

UserMapper

package com.yj.dao;import org.springframework.stereotype.Repository;import com.yj.model.User;@Repositorypublic interface UserMapper {    int deleteByPrimaryKey(Integer id);    int insert(User record);    int insertSelective(User record);    User selectByPrimaryKey(Integer id);    int updateByPrimaryKeySelective(User record);    int updateByPrimaryKey(User record);}

UserMapper

id, name
delete from user where id = #{id,jdbcType=INTEGER}
insert into user (name) values (#{name,jdbcType=VARCHAR})
insert into user
name,
#{name,jdbcType=VARCHAR},
update user
name = #{name,jdbcType=VARCHAR},
where id = #{id,jdbcType=INTEGER}
update user set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER}

UserService

package com.yj.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.yj.dao.UserMapper;import com.yj.model.User;@Servicepublic class UserService {	@Autowired	private UserMapper userMapper;		public User selectByPrimaryKey(Integer id) {		return userMapper.selectByPrimaryKey(id);	}}

User

package com.yj.model;public class User {    private Integer id;    private String name;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name == null ? null : name.trim();    }}

UserController

package com.yj.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.yj.service.UserService;@RestControllerpublic class UserController {	@Autowired	private UserService userService;	@RequestMapping("/getUser")	public void getUser(@RequestBody int id) {		userService.selectByPrimaryKey(id);	}}

进行Junit单元测试,成功的查询出了数据,查看Druid监控地址,也看到了监控数据

转载地址:http://lpsjn.baihongyu.com/

你可能感兴趣的文章
快速入门Scala③ scala循环操作
查看>>
SparkCore快速入门及介绍
查看>>
Spark快速入门API① Transformation转换算子
查看>>
SparkSQL介绍及快速入门
查看>>
SparkSQL快速入门DataFrame与DataSet
查看>>
SparkSQL查询风格SQL与DSL介绍及使用
查看>>
SparkSQL使用IDEA快速入门DataFrame与DataSet
查看>>
SparkSQL实现wordCount与资源转换
查看>>
SparkSQL 自定义函数UDF与UDAF
查看>>
SparkSQL介绍并实现开窗函数
查看>>
快速入门Shell脚本(1)——Shell脚本的介绍
查看>>
快速入门Shell脚本(2)——系统变量与自定义变量
查看>>
快速入门Shell脚本(3)——条件判断语句与循环
查看>>
快速入门Shell脚本(4)——常用的函数操作
查看>>
快速入门Shell脚本(5)——Shell的这些工具你都知道了吗?
查看>>
快速入门Shell脚本(6)——学会这些大厂面试题你还害怕面试官问你?(建议收藏)
查看>>
快速入门Flink(1)——Flink介绍与架构体系
查看>>
快速入门Flink(2)——Flink集群环境搭建(3台节点 建议收藏)
查看>>
快速入门Flink(3)——Flink运行架构(面试必问,建议收藏)
查看>>
MySQl5.7 Linux安装教程(全网最全,建议收藏)
查看>>