您的位置:首页 > 编程语言 > Java开发

Spring Boot整合MyBatis

2016-08-21 16:02 627 查看
转:http://blog.didispace.com/springbootmybatis/,http://412887952-qq-com.iteye.com/blog/2303121
http://blog.csdn.net/u013187139/article/details/68944972 http://blog.csdn.net/gebitan505/article/details/54929287
整合MyBatis

新建Spring Boot项目,

pom.xml中引入依赖

这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问

引入连接mysql的必要依赖mysql-connector-java

引入整合MyBatis的核心依赖mybatis-spring-boot-starter

这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖

<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.example</groupId>
<artifactId>springbootmybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>

<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-boot-starter-test 模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root


=======

使用druid数据源

spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
# 使用druid数据源 使用默认数据源下面的注解要注销或者更改其数据源根据具体数据源书写配置参数
type: com.alibaba.druid.pool.DruidDataSource
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


注入数据源

package com.example.configuration;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

private RelaxedPropertyResolver propertyResolver;

@Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
}

@Bean(destroyMethod = "close", initMethod = "init")
public DataSource writeDataSource() throws SQLException {
System.out.println("注入druid!!!");

DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(propertyResolver.getProperty("url"));
dataSource.setUsername(propertyResolver.getProperty("username"));//用户名
dataSource.setPassword(propertyResolver.getProperty("password"));//密码
dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));
dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));
dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));
dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));
dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));
dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow")));
dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle")));
dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn")));
dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements")));
dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements")));
//配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
dataSource.setFilters(propertyResolver.getProperty("filters"));
return dataSource;
}

}

使用@ConfigurationProperties自动注入配置参数

加入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DataBaseConfiguration {

@Bean(destroyMethod = "close", initMethod = "init")
@ConfigurationProperties("spring.datasource")
public com.alibaba.druid.pool.DruidDataSource dataSource() {

System.out.println("注入druid!!!");
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}


使用注解

使用MyBatis

在Mysql中创建User表,包含id(BIGINT)、name(INT)、age(VARCHAR)字段。同时,创建映射对象User
public class User {

private Long id;
private String name;
private Integer age;

// 省略getter和setter

}

创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作

<pre name="code" class="html">package com.example.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.domain.User;

@Mapper
public interface UserMapper {

@Select("SELECT * FROM USER WHERE NAME = #{name}")
User findByName(@Param("name") String name);

@Update("UPDATE user SET age=#{age} WHERE name=#{name}")
void update(User user);

@Insert("INSERT INTO USER(NAME,AGE) VALUES(#{name},#{age})")
int insert(@Param("name") String name, @Param("age") Integer age);

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);

@Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);

@Results({
@Result(property="name",column="name"),
@Result(property="age",column="age")
})
@Select("SELECT name, age FROM user")
List<User> findAll();
}



创建Spring Boot主类

</pre><pre name="code" class="html">package com.example;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
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.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.example.domain.User;
import com.example.mapper.UserMapper;

@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes=Application.class)
@SpringApplicationConfiguration(classes=Application.class)
public class ApplicationTests {

@Autowired
private UserMapper userMapper;

@Test
@Rollback
public void findByName(){
//userMapper.insert("AAA", 20);
User u = userMapper.findByName("AAA");
System.out.println(u);
Assert.assertEquals(20, u.getAge().intValue());
}
@Test
@Rollback
public void update(){
User user = new User();
user.setAge(110);
user.setName("AAA");
userMapper.update(user);
User u = userMapper.findByName("AAA");
System.out.println(u);
Assert.assertEquals(110, u.getAge().intValue());
}

@Test
@Rollback
public void insertByUser(){
User user = new User();
user.setAge(12);
user.setName("BBB");
userMapper.insertByUser(user);
User u = userMapper.findByName("BBB");
System.out.println(u);
Assert.assertEquals(12, u.getAge().intValue());
}

@Test
@Rollback
public void insertByMap(){
Map<String, Object> map = new HashMap<>();
map.put("name", "CCC");
map.put("age", 40);
userMapper.insertByMap(map);
User u = userMapper.findByName("CCC");
System.out.println(u);
Assert.assertEquals(40, u.getAge().intValue());
}
@Test
@Rollback
public void delete(){
userMapper.delete(1L);
java.util.List<User> findAll = userMapper.findAll();
System.out.println(findAll);
}

}

传参方式

下面通过几种不同传参方式来实现前文中实现的插入操作。

使用@Param

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);

这种方式很好理解,@Param中定义的name对应了SQL中的#{name},age对应了SQL中的#{age}。

使用Map

如下代码,通过Map对象来作为传递参数的容器:

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);


对于Insert语句中需要的参数,我们只需要在map中填入同名的内容即可,具体如下面代码所示:

Map<String, Object> map = new HashMap<>();
map.put("name", "CCC");
map.put("age", 40);
userMapper.insertByMap(map);


使用对象

除了Map对象,我们也可直接使用普通的Java对象来作为查询条件的传参,比如我们可以直接使用User对象:

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);


这样语句中的#{name}、#{age}就分别对应了User对象中的name和age属性。

增删改查

MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,在之前的示例中演示了@Insert,下面针对User表做一组最基本的增删改查作为示例:

public interface UserMapper {

@Select("SELECT * FROM user WHERE name = #{name}")
User findByName(@Param("name") String name);

@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);

@Update("UPDATE user SET age=#{age} WHERE name=#{name}")
void update(User user);

@Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);
}


返回结果的绑定

对于增、删、改操作相对变化较小。而对于“查”操作,我们往往需要进行多表关联,汇总计算等操作,那么对于查询的结果往往就不再是简单的实体对象了,往往需要返回一个与数据库实体不同的包装类,那么对于这类情况,就可以通过@Results和@Result注解来进行绑定,具体如下:

@Results({
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
@Select("SELECT name, age FROM user")
List<User> findAll();


在上面代码中,@Result中的property属性对应User对象中的成员名,column对应SELECT出的字段名。只对User对应中的name和age对象做了映射配置

添加分页插件

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>


package com.example.configuration;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;

@Configuration
public class MyBatisConfiguration {

@Bean
public PageHelper pageHelper(){
System.out.println("MyBatisConfiguration.pageHelper()");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}

}


这个使用起来特别的简单,只是在原来查询的代码之前加入了一句:

 PageHelper.startPage(1,1);

第一个参数是第几页;

第二个参数是每页显示条数。

@RequestMapping("/allUser")
public List<User> findAllUser() {
PageHelper.startPage(1, 2);
return userService.findUser();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: