Spring Boot使用mybatis连接mysql
使用IDEA创建一个spring boot项目,项目名为springbootstudy,使用maven管理jar包。
1,修改pom.xml配置,配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.jack</groupId>
<artifactId>springbootstudy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springbootstudy</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<!--feign方式远程调用需要的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<!-- 与数据库操作相关的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mybatis与springboot整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 使用druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mybatis包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
需要听见mysql驱动包,mybatis包,mybatis和spring正和的包,采用阿里巴巴的数据druid做数据库连接池,mybatis与spring boot整合的包,spring boot的jdbc操作的包。
2,修改application.yml配置文件,代码如下:
server:
port: 9092
spring:
application:
name: spring-cloud-consumer
datasource:
name: test
url: jdbc:mysql://192.168.9.107:3306/jack?characterEncoding=utf8&useSSL=true
username: root
password: root
#使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis:
mapperLocations: classpath:mapper/*.xml #指定*Mapper.xml的位置
#设置日志级别,打印mybatis的日志
logging:
level:
root: debug
注意:需要开启mybatis操作的日志的话,需要修改loggin.level.root=debug,在resource目录下创建mapper目录,用于存放mybatis操作的sql文件。
3,创建mybatis的配置类,代码如下:
package com.jack.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 javax.sql.DataSource;
/**
* Created by jackc on 2017/7/20.
*/
@Configuration
public class MybatisConfig {
/**
* 注入环境变量的值
*/
@Autowired
private Environment environment;
/**
* 获取数据源DataSource
* @return
*/
@Bean
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
druidDataSource.setUsername(environment.getProperty("spring.datasource.username"));
druidDataSource.setPassword(environment.getProperty("spring.datasource.password"));
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.setTimeBetweenEvictionRunsMillis(Long.parseLong(environment.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")));
druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(environment.getProperty("spring.datasource.minEvictableIdleTimeMillis")));
druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
druidDataSource.setTestWhileIdle(Boolean.parseBoolean(environment.getProperty("spring.datasource.testWhileIdle")));
druidDataSource.setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnBorrow")));
druidDataSource.setTestOnReturn(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnReturn")));
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);
LogFactory.useLog4JLogging();
//添加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 sqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
/**
* 增加事务
* @param druidDataSource
* @return
*/
@Bean
public DataSourceTransactionManager transactionManager(DataSource druidDataSource) {
return new DataSourceTransactionManager(druidDataSource);
}
}
4,创建一个配置类,进行mapper接口的扫描,通过调用这些接口,进而调用配置的sql操作数据库。
package com.jack.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by jack on 2017/7/20.
*/
@Configuration
//注意,由于MabatisMapperScanConfig执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MybatisConfig.class)
public class MabatisMapperScanConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//注意这里的sqlSessionFactory就是MybatisConfig里面的sqlSessionFactoryBean方法,注解bean的名字
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//接口路径,通过这些接口调用sql的配置,操作数据库
mapperScannerConfigurer.setBasePackage("com.jack.mapper");
return mapperScannerConfigurer;
}
}
5,创建一个一个com.jack.mapper包,里面存放数据库操作的接口文件,下面创建一个测试的接口,代码如下:
package com.jack.mapper;
import com.google.common.annotations.VisibleForTesting;
import com.jack.entity.Test;
import java.util.List;
/**
* Created by jack on 2017/7/20.
* 接口,对Test表进行操作
*/
public interface TestMapper {
Test findTestById(int id);
int add(Test test);
int deleteById(int id);
int updateByID(Test test);
List<Test> findByName(String name);
}
6,创建一个com.jack.entity包里面存放对应的数据库表的类,测试类代码如下:
package com.jack.entity;
/**
* Created by jack on 2017/7/20.
*/
public class Test {
private int id;
private String name;
private String note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "Test{" +
"id=" + id +
", name='" + name + '\'' +
", note='" + note + '\'' +
'}';
}
}
7,在resource/mapper目录下创建一个TestMapper.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.jack.mapper.TestMapper" >
<!--通过id查找-->
<select id="findTestById" parameterType="int" resultType="com.jack.entity.Test">
SELECT * from test where id = #{id}
</select>
<!--增加-->
<insert id="add" parameterType="com.jack.entity.Test">
INSERT INTO test(name,note) VALUES (#{name},#{note})
</insert>
<!--删除-->
<delete id="deleteById" parameterType="int">
DELETE FROM test where id = #{id}
</delete>
<!--更新-->
<update id="updateByID" parameterType="com.jack.entity.Test">
UPDATE test SET NAME =#{name},note =#{note} where id = #{id}
</update>
<!--模糊查询-->
<select id="findByName" parameterType="string" resultType="com.jack.entity.Test">
SELECT id,name,note from test where name like concat('%',#{name},'%')
</select>
</mapper>
8,创建一个测试的controller,代码如下:
package com.jack.controller;
import com.jack.entity.Test;
import com.jack.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by jack on 2017/7/20.
*/
@RestController
public class TestController {
@Autowired
TestMapper testMapper;
/**
* 通过id进行查询
* @return
*/
@RequestMapping(value = "/find/id")
public String fingTestById(){
return testMapper.findTestById(1).toString();
}
/**
* 添加
* @return
*/
@RequestMapping(value = "/add")
public String addTest(){
Test test = new Test();
test.setName("jack add");
test.setNote("this is add element to test table");
int result= testMapper.add(test);
System.out.println("add result ="+result);
if (result >0) {
return "添加成功";
}else {
return "添加失败";
}
}
/**
* 通过id删除
* @return
*/
@RequestMapping(value = "/delete")
public String deleteTestById(){
int result= testMapper.deleteById(5);
System.out.println("deleteTestById result ="+result);
if (result > 0) {
return "删除成功";
} else {
return "删除失败";
}
}
/**
* 通过id更新
* @return
*/
@RequestMapping(value = "/update")
public String updateTestById(){
Test test = new Test();
test.setId(6);
test.setName("this is updete name ");
test.setNote("this is update note");
int result= testMapper.updateByID(test);
System.out.println("updateTestById result ="+result);
if (result > 0) {
return "更新成功";
} else {
return "更新失败";
}
}
/**
* 通过名字进行模糊查询
* @return
*/
@RequestMapping(value = "/findname")
public String findByName(){
List<Test> result= testMapper.findByName("jack");
System.out.println("updateTestById result ="+result.toString());
if (result != null) {
return "更新成功";
} else {
return "更新失败";
}
}
}
9,测试数据库的设计
1,创建一个名为jack的数据库
2,创建一个test表,sql语句如下:
/*
Navicat MySQL Data Transfer
Source Server : MyLocalMySQL192.168.9.107
Source Server Version : 50718
Source Host : 192.168.9.107:3306
Source Database : jack
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2017-07-21 14:24:34
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for test
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`note` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
10,启动这个项目,通过浏览器,输入相应的路径进行测试,通过controller调用接口,进而调用sql操作数据库,看日志,有mybatis调用的日志输出,查看数据库,看对数据库表的操作后有什么变化。
上一篇: javascript每日必学之继承_javascript技巧
下一篇: css 图片垂直居中总结
推荐阅读
-
spring boot开发遇到坑之spring-boot-starter-web配置文件使用教程
-
使用Spring Boot创建Web应用程序的示例代码
-
Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图的方法
-
Spring Boot整合mybatis并自动生成mapper和实体实例解析
-
Spring boot 使用JdbcTemplate访问数据库
-
mybatis-4 mybatis与spring结合使用及原理解析
-
Spring boot中使用Spring-data-jpa方便快捷的访问数据库(推荐)
-
spring boot使用自定义配置的线程池执行Async异步任务
-
详解如何在spring boot中使用spring security防止CSRF攻击
-
Spring Boot + Mybatis多数据源和动态数据源配置方法