Mybatis 官方提供了 mybatis-spring-boot-starter
https://github.com/mybatis/spring-boot-starter
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
使用spring boot 的starter pom
需要导入 mybatis-spring-boot-starter 和 数据库连接相关的配置
pom.xml
4.0.0
com.ibigsea
bootdao
0.0.1-SNAPSHOT
jar
bootdao
http://maven.apache.org
UTF-8
1.3.1.RELEASE
org.springframework.boot
spring-boot-starter-web
${boot.version}
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
mysql
mysql-connector-java
5.1.38
com.alibaba
druid
1.0.5
org.springframework.boot
spring-boot-starter-test
${boot.version}
test
org.springframework.boot
spring-boot-maven-plugin
是不是很方便,mybatis的starter pom里面依赖了mybatis和spring相关的jar
只需导入一个就OK了
这里采用的是阿里巴巴的druid数据连接池
为了方便使用 yml配置文件
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: 3000
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 + "]";
}
}
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 queryAll();
}
UserMapper.xml
insert into t_user(username,age) values(#{userName,jdbcType=VARCHAR},#{age,jdbcType=NUMERIC})
update t_user set
username = #{userName,jdbcType=VARCHAR} ,
age = #{age,jdbcType=NUMERIC}
where id = #{id,jdbcType=NUMERIC}
delete from t_user where id = #{id,jdbcType=NUMERIC}
启动类 App.class
package com.ibigsea.bootdao;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
//启注解事务管理
@EnableTransactionManagement
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
这里使用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})
//相当于 --spring.profiles.active=dev
@ActiveProfiles(value="dev")
public class AppTest {
@Autowired
private UserMapper mapper;
@Test
public void testInsert(){
User user = new User();
user.setUserName("张三");
user.setAge(23);
mapper.save(user);
System.out.println("插入用户信息"+user.getUserName());
}
}
运行结果:
Ok 数据库这边也有数据了
表结构这边就不提供了 , 就一个很简单的表 自己创建一个就可以了
查询:
@Test
public void testSelect(){
User user = mapper.selectById(1);
System.out.println(user);
}
@Test
public void testUpdate(){
User user = mapper.selectById(1);
System.out.println(user);
user.setAge(24);
mapper.updateById(user);
user = mapper.selectById(1);
System.out.println(user);
}
Mybatis相关的配置
Spring boot 在运行的时候会进行自动配置
读取到 mybatis-spring-boot-autoconfigure 里面的spring.factories,然后自动配置
就是下面这个类
这个方法使用了PostConstruct注解,在初始化的时候去加载mybatis的配置文件,然后创建SqlSessionFactory等
Mybatis自动配置会自动创建 sqlSessionFactory和SqlSessionTemplate
这个东西 就是 加载在注解了@Mapper的类
如果不喜欢在mapper上面加注解的话,也可以通过@MapperScan
这样子:
这样就OK啦
关于事务方面
在启动类上面添加
@EnableTransactionManagement注解
然后在类上面或者方法上面添加@Transactional注解
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")
//在方法和类上面都可以
@Transactional
public class UserService {
@Autowired
private UserMapper mapper;
public void insetUser() throws Exception {
User user = new User();
user.setUserName("李四");
user.setAge(23);
mapper.save(user);
System.out.println("插入用户信息"+user.getUserName());
if (user.getUserName().equals("李四")) {
throw new IllegalArgumentException("出现异常QAQ");
}
user = new User();
user.setUserName("李四11111");
user.setAge(23);
mapper.save(user);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {App.class})
//相当于 --spring.profiles.active=dev
@ActiveProfiles(value="dev")
@EnableTransactionManagement
public class AppTest {
@Autowired
private UserService userService;
@Test
public void testTransactional() throws Exception {
userService.insetUser();
}
}
数据库结果
我们吧@Transactional注解去掉 或者去掉 @EnableTransactionManagement注解
测试下看看
数据被插入~~~~~