Prior to the integration of MyBatis, to build a basic Spring Boot project open Spring Boot . Then introduced mybatis-spring-boot-starter and a database connected to the drive (as used herein, relational database Oracle 11g).
mybatis-spring-boot-starter
Introduced in the pom:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
Different versions of MyBatis and Spring Boot corresponding version is not the same, specifically to see the official document: http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ .
By dependency: tree command to view mybatis-spring-boot-starter What are implicit dependence:
+- org.mybatis.spring.boot:mybatis-spring-boot-starter:jar:1.3.1:compile
| +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.5.9.RELEASE:compile
| | +- org.apache.tomcat:tomcat-jdbc:jar:8.5.23:compile
| | | \- org.apache.tomcat:tomcat-juli:jar:8.5.23:compile
| | \- org.springframework:spring-jdbc:jar:4.3.13.RELEASE:compile
| | \- org.springframework:spring-tx:jar:4.3.13.RELEASE:compile
| +- org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:jar:1.3.1:compile
| +- org.mybatis:mybatis:jar:3.4.5:compile
| \- org.mybatis:mybatis-spring:jar:1.3.1:compile
It may be found to contain the spring-boot-starter-jdbc dependent, using default tomcat-jdbc data source.
Introduced ojdbc6
Due to copyright reasons, we need to rely ojdbc6.jar installed to the local maven repository, then it can be configured in the pom.
Ojdbc6.jar After downloading the file, place it under relatively easy to find a directory, such as D root directory. Then run the following command:
C:\Users\Administrator>mvn install:install-file -Dfile=D:/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=6.0 -
Dpackaging=jar -DgeneratePom=true
...
[INFO] --- maven-install-plugin:2.4:install-file (default-cli) @ standalone-pom ---
[INFO] Installing D:\ojdbc6.jar to D:\m2\repository\com\oracle\ojdbc6\6.0\ojdbc6-6.0.jar
[INFO] Installing C:\Users\ADMINI~1\AppData\Local\Temp\mvninstall9103688544010617483.pom to D:\m2\repository\com\oracle\ojdbc
6\6.0\ojdbc6-6.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.940 s
[INFO] Finished at: 2017-08-13T15:06:38+08:00
[INFO] Final Memory: 6M/145M
[INFO] ------------------------------------------------------------------------
Followed by introduction in the pom:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>6.0</version>
</dependency>
groupid here is specified when you install before -Dgroupid value, artifactid is the value you specified when you install the -Dartifactid, version, too.
Druid data source
Druid is a relational database connection pool, Ali Baba is an open source project, address: https://github.com/alibaba/druid . Druid function not only provides the connection pool, it also provides monitoring capabilities, you can view the work of the database connection pool and SQL queries in real time.
Configuration Druid dependence
Druid offers corresponding starter for the Spring Boot Project:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
Data source configuration Druid
See above mybatis starter by implicit dependency discovery, the default data type Spring Boot source configuration is org.apache.tomcat.jdbc.pool.Datasource , Druid connection pool to use, you need to configure the application.yml:
Server:
context-path: / Web Spring: DataSource: druid: # database access configuration using druid data source type: com.alibaba.druid.pool.DruidDataSource Driver-class-name: oracle.jdbc.driver.OracleDriver URL: JDBC: Oracle: Thin: @localhost: 1521: ORCL username: Scott password: 123456 # connection pool configuration Initial-size:. 5 min-IDLE:. 5 max-Active: 20 is # connection waiting timeout max the wait-: 30000 # configure the detection an idle connection can be closed interval time-BETWEEN-eviction-the runs of millis-: 60000 # connector disposed in the pool of the minimum lifetime min-evictable-iDLE-time-of millis: 300000 Validation-Query: SELECT '. 1' from Dual
the while-IDLE-Test: to true
Test-ON-BORROW: to false
Test-return-ON: to false
# open PSCache, and specifies the size of each connection PSCache
the pool--Prepared statements: to true
max-Open--Prepared statements: 20 is
Prepared the pool---max Statement-size-per-Connection: 20 is
# intercepted Filters configuration monitoring statistics, after removing the monitoring interface can not sql statistics, 'wall' firewalls
Filters: STAT, Wall
# monitoring the Spring AOP entry point, such as xyzservice *, a plurality of comma separated.
AOP-Patterns:. com.springboot.servie * # WebStatFilter arranged Web-STAT-filter: Enabled: to true # Add filter rule URL-pattern: / * # ignore filter format exclusions: '* .js, *. GIF, *. JPG, *. PNG, *. CSS, *. ICO, / Druid / *' # StatViewServlet configure
the servlet-View-STAT:
Enabled: to true
when the access path is # / druid, jump to StatViewServlet
url-pattern: / Druid / *
# is able to reset the data in
the RESET-enable: false
# account needs a password to access the console
login- username: Druid
the Login-password: druid123
# IP whitelist
# the allow: 127.0.0.1
# IP blacklist (when present together, deny takes precedence over the allow)
# deny: 192.168.1.218 # configure StatFilter filter: STAT: log-SLOW-SQL : true
Not only the above-described configuration is configured as a Druid connection pool, but also opens up the monitoring Druid. Other configurations may refer to the official wiki-- https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
At this point, run the project, visit HTTP: // localhost: 8080 / Web / Druid :
Enter the account password to see Druid monitor background:
关于Druid的更多说明,可查看官方wiki——https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
使用MyBatis
使用的库表:
CREATE TABLE "SCOTT"."STUDENT" (
"SNO" VARCHAR2(3 BYTE) NOT NULL ,
"SNAME" VARCHAR2(9 BYTE) NOT NULL ,
"SSEX" CHAR(2 BYTE) NOT NULL
);
INSERT INTO "SCOTT"."STUDENT" VALUES ('001', 'KangKang', 'M ');
INSERT INTO "SCOTT"."STUDENT" VALUES ('002', 'Mike', 'M ');
INSERT INTO "SCOTT"."STUDENT" VALUES ('003', 'Jane', 'F ');
创建对应实体:
public class Student implements Serializable{
private static final long serialVersionUID = -339516038496531943L;
private String sno;
private String name;
private String sex;
// get,set略
}
创建一个包含基本CRUD的StudentMapper:
public interface StudentMapper {
int add(Student student);
int update(Student student);
int deleteByIds(String sno);
Student queryStudentById(Long id);
}
StudentMapper的实现可以基于xml也可以基于注解。
使用注解方式
继续编辑StudentMapper:
@Component
@Mapper
public interface StudentMapper {
@Insert("insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex})")
int add(Student student);
@Update("update student set sname=#{name},ssex=#{sex} where sno=#{sno}")
int update(Student student);
@Delete("delete from student where sno=#{sno}")
int deleteBysno(String sno);
@Select("select * from student where sno=#{sno}")
@Results(id = "student",value= {
@Result(property = "sno", column = "sno", javaType = String.class),
@Result(property = "name", column = "sname", javaType = String.class),
@Result(property = "sex", column = "ssex", javaType = String.class)
})
Student queryStudentBySno(String sno);
简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,动态SQL语句需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。具体可参考MyBatis官方文档:http://www.mybatis.org/mybatis-3/zh/java-api.html。
使用xml方式
使用xml方式需要在application.yml中进行一些额外的配置:
mybatis:
# type-aliases扫描路径
# type-aliases-package:
# mapper xml实现扫描路径
mapper-locations: classpath:mapper/*.xml
property:
order: BEFORE
测试
接下来编写Service:
public interface StudentService {
int add(Student student);
int update(Student student);
int deleteBysno(String sno);
Student queryStudentBySno(String sno);
}
实现类:
@Service("studentService")
public class StudentServiceImp implements StudentService{
@Autowired
private StudentMapper studentMapper;
@Override
public int add(Student student) {
return this.studentMapper.add(student);
}
@Override
public int update(Student student) {
return this.studentMapper.update(student);
}
@Override
public int deleteBysno(String sno) {
return this.studentMapper.deleteBysno(sno);
}
@Override
public Student queryStudentBySno(String sno) {
return this.studentMapper.queryStudentBySno(sno);
}
}
编写controller:
@RestController
public class TestController {
@Autowired
private StudentService studentService;
@RequestMapping( value = "/querystudent", method = RequestMethod.GET)
public Student queryStudentBySno(String sno) {
return this.studentService.queryStudentBySno(sno);
}
}
完整的项目目录如下图所示:
启动项目访问:http://localhost:8080/web/querystudent?sno=001:
查看SQL监控情况:
可看到其记录的就是刚刚访问/querystudent得到的SQL。