Mybatis officially provided the Mybatis-spring-boot-starter
Https://github.com/mybatis/spring-boot-starter
Http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ Example
Use the Spring Boot starter POM
Need to import Mybatis-spring-boot-starter and database connection related configuration
Pom.xml
<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.ibigsea</groupId> <artifactid>bootdao </artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name >bootdao</name> <url>http://maven.apache.org</url> <properties> < Project.build.sourceencoding>utf-8</project.build.sourceencoding> <boot.version>1.3.1.release </boot.version> </properties> <dependencies> <dependency> <groupid>org.springframewo Rk.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> <version>${ boot.version}</version> </dependency> <dependency> <groupid>org.mybatis.spring.boOt</groupid> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</
Version> </dependency> <!--mysql driver--<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency&
Gt <!--database connection pool-<dependency> <groupId>com.alibaba</groupId> <artifactid>druid</ar tifactid> <version>1.0.5</version> </dependency> <dependency> <groupid>org.spri Ngframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <version>${ boot.version}</version> <scope>test</scope> </dependency> </dependencies> <build&
Gt <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring -boot-maven-plugin</artifactid> </plugin> </plugins> </build> </project>
is not very convenient, MyBatis starter Pom is dependent on the MyBatis and spring-related jar
Just import one and it's OK.
Alibaba's Druid data connection pool is used here.
To facilitate the use of the YML configuration file
Application.yml
---
spring:
profiles:dev
DataSource:
name:mydb
Type:com.alibaba.druid.pool.DruidDataSource
url:jdbc:mysql://127.0.0.1:3306/mytestdb
username:root
password:123456
driver-class-name: Com.mysql.jdbc.Driver
minidle:1
maxactive:2
initialsize:1
timebetweenevictionrunsmillis:
minevictableidletimemillis:300000
validationquery:select ' ZTM ' from DUAL
testwhileidle:true
testonborrow:false
testonreturn:false
mybatis:
mapperlocations:classpath*:com/ibigsea/ Bootdao/mapper/*.xml
typeAliasesPackage:com.ibigsea.bootdao.entity
User.java
Package com.ibigsea.bootdao.entity;
Import java.io.Serializable;
public class User implements Serializable {
private static final long serialversionuid = 8809101560720973267L;
Private Integer ID;
Private String userName;
Private Integer age;
Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
this.id = ID;
}
Public String GetUserName () {
return userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public Integer Getage () {
return age;
}
public void Setage (Integer age) {
this.age = age;
}
@Override public
String toString () {
return ' User [id= + ID + ', username= "+ UserName +", age= "+ Age +"] "; c27/>}
}
Usermapper.java
Package com.ibigsea.bootdao.mapper;
Import java.util.List;
Import Org.apache.ibatis.annotations.Mapper;
Import Com.ibigsea.bootdao.entity.User;
@Mapper Public
interface Usermapper {
int save (user user);
User Selectbyid (Integer ID);
int Updatebyid (user user);
int Deletebyid (Integer ID);
List<user> Queryall ();
}
<p>UserMapper.xml</p>
<?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.ibigsea.bootdao.mapper.UserMapper" > <insert id= "Save" parametertype= " Com.ibigsea.bootdao.entity.User "> INSERT into T_user (username,age) VALUES (#{username,jdbctype=varchar},#{age, Jdbctype=numeric}) </insert> <select id= "Selectbyid" resulttype= "Com.ibigsea.bootdao.entity.User" > Sele CT * from t_user where id = #{id,jdbctype=numeric} </select> <update id= "Updatebyid" parametertype= "Com.ibigs Ea.bootdao.entity.User "> Update t_user set username = #{username,jdbctype=varchar}, age = #{age,jdbctype=numer IC} WHERE id = #{id,jdbctype=numeric} </update> <delete id= "Deletebyid" > Delete from T_user where id = #{id,jdbctype=numeric} </delete> <select id= "Queryall" resulttype= "com.ibigsea.bootdao.entity.User" > SE Lect * FROM T_user </select> </mapper>
Startup class App.class
Package Com.ibigsea.bootdao;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*
/@SpringBootApplication//Start annotation transaction management
@EnableTransactionManagement public
class App {
public static void Main (string[] args) {
System.out.println ("Hello world!");
}
}
This is tested using test.
Package Com.ibigsea.bootdao;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.boot.test.SpringApplicationConfiguration;
Import Org.springframework.test.context.ActiveProfiles;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Import Com.ibigsea.bootdao.entity.User;
Import Com.ibigsea.bootdao.mapper.UserMapper;
@RunWith (Springjunit4classrunner.class)
@SpringApplicationConfiguration (classes = {App.class})
//equivalent --spring.profiles.active=dev
@ActiveProfiles (value= "dev") public
class Apptest {
@Autowired
private Usermapper mapper;
@Test public
void Testinsert () {
User user = new User ();
User.setusername ("Zhang San");
User.setage (+);
Mapper.save (user);
System.out.println ("Insert User Information" +user.getusername ());
}
}
Operation Result:
Ok, there's data on this side of the database.
Table structure is not provided on this side, just a very simple table to create one on their own.
Inquire:
@Test public
void Testselect () {
User user = Mapper.selectbyid (1);
SYSTEM.OUT.PRINTLN (user);
}
Update
@Test public
void Testupdate () {
User user = Mapper.selectbyid (1);
SYSTEM.OUT.PRINTLN (user);
User.setage ();
Mapper.updatebyid (user);
user = Mapper.selectbyid (1);
SYSTEM.OUT.PRINTLN (user);
}
MyBatis Related Configurations
mybatisautoconfiguration
Spring boot is automatically configured when it is run
Read the spring.factories inside the mybatis-spring-boot-autoconfigure and configure it automatically
is the following class
This method uses the Postconstruct annotation to load the MyBatis configuration file at initialization time, and then create sqlsessionfactory , etc.
MyBatis Auto-configuration automatically creates sqlsessionfactory and sqlsessiontemplate
This thing is loaded in the annotated @mapper class
If you do not like to annotate the mapper above, you can also pass @MapperScan
This way:
That's OK.
On the aspect of the transaction
Above the startup class, add
@EnableTransactionManagement annotations
Then add @transactional annotations above the class or on the method
Package com.ibigsea.bootdao.service;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import org.springframework.transaction.annotation.Transactional;
Import Com.ibigsea.bootdao.entity.User;
Import Com.ibigsea.bootdao.mapper.UserMapper;
@Service ("UserService")
Both methods and classes can be
@Transactional public
class UserService {
@Autowired
private usermapper mapper;
public void Insetuser () throws Exception {
User user = new user ();
User.setusername ("John Doe");
User.setage (+);
Mapper.save (user);
System.out.println ("Insert User Information" +user.getusername ());
if (User.getusername () equals ("John Doe")) {
throw new IllegalArgumentException ("Exception Qaq");
}
user = new User ();
User.setusername ("Li 411,111");
User.setage (+);
Mapper.save (user);
}
}
Test class
@RunWith (Springjunit4classrunner.class)
@SpringApplicationConfiguration (classes = {App.class})
//equivalent --spring.profiles.active=dev
@ActiveProfiles (value= "Dev")
@EnableTransactionManagement
Public Class Apptest {
@Autowired
private userservice userservice;
@Test public
void Testtransactional () throws Exception {
userservice.insetuser ();
}
}
Database Results
Let's do it. @transactional annotations Remove or remove @EnableTransactionManagement annotations
Take a look at the test
Data is inserted ~~~~~