Spring Boot mybatisを使ってmysqlを接続します.
IDEAを使ってspring bootプロジェクトを作成します.プロジェクト名はspring boot studyで、Mavenを使ってjarパッケージを管理します.
1,pom.xmlの構成を変更します.構成は以下の通りです.
2,appication.ymlのプロファイルを変更します.コードは以下の通りです.
3,mybatisの配置類を作成します.コードは以下の通りです.
1,jackというデータベースを作成します.
2,testテーブルを作成します.sql文は以下の通りです.
1,pom.xmlの構成を変更します.構成は以下の通りです.
4.0.0
com.jack
springbootstudy
0.0.1-SNAPSHOT
jar
springbootstudy
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.4.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-eureka-server
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-starter-feign
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-starter-ribbon
1.3.1.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
mysql
mysql-connector-java
com.alibaba
druid
1.1.1
org.mybatis
mybatis
3.4.4
org.mybatis
mybatis-spring
1.3.1
org.springframework.boot
spring-boot-maven-plugin
mysqlドライババッグ、mybatisバッグ、mybatisとspringが合っているカバン、アリババのデータdruidを採用してデータベース接続池、mybatisとspring bootが統合したカバン、spring bootのjdbc操作のカバンを作る必要があります.2,appication.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操作のログを開くには、loging.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,comp.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 findByName(String name);
}
6、comp.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ファイルを作成します.コードは以下の通りです.
INSERT INTO test(name,note) VALUES (#{name},#{note})
DELETE FROM test where id = #{id}
UPDATE test SET NAME =#{name},note =#{note} where id = #{id}
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 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,このプロジェクトを起動して、ブラウザを通じて、相応のパスを入力してテストを行い、controlを通じてインターフェイスを呼び出して、sql操作データベースを呼び出して、ログを見て、mybatis呼び出しのログ出力があります.データベースを調べて、データベーステーブルの操作を見て、どのような変化がありますか?