Spring-Boot整合mybatis(一),使用默认的数据库链接池

最近工做比较忙,好久没写博客了,抱歉,之前springboot项目使用的是JPA标准,使用hibernate来实现的,最新心血来潮,试试springboot整合mybatis试试,因而找了官方文档来进行配置下,下面就是正文了java

 

先介绍一下开发环境:mysql

  1. jdk版本是1.8
  2. springboot的版本是1.4.1
  3. 开发工具为 intellij idea

 

首先咱们先引入mybatis的依赖,在项目的pom文件中添加如下内容:spring

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.1.1</version>
</dependency>

 

------------------------------------分割线-------------------------------------sql

引入依赖后,在数据库执行如下SQL数据库

create table city (id int primary key auto_increment, name varchar(32), state varchar(32), country varchar(32));
insert into city (name, state, country) values ('BeiJing', 'OFF', 'CN');  

上面是建立表跟插入一条数据,方便咱们测试是否执行apache

 

而后咱们建立一个mappertomcat

 

 

//mapper注解
@Mapper
public interface CityMapper {
 
    //SQL注解
    @Select("SELECT * FROM CITY WHERE state = #{state}")
    City findByState(@Param("state") String state);

}

 

PS注解描述:springboot

    @Mapper 表示这是个mapper,相似之前在xml配置的mapper,只不过这里使用注解不使用xml而已,若是不是在默认路径下,还须要配合@MapperScan注解使用,不然会扫描不到@Mapper注解的路径mybatis

    @Select SQL注解,里面内容是须要执行的SQL,相似注解还有@Update等app

    @Param 参数注解,用于SQL参数注入使用

 

 

建立好mapper后,咱们须要建立一个映射实体类,用于对象跟表之间的映射,咱们只须要建立一个普通的java对象就行了

public class City {

	private Long id;

	private String name;

	private String state;

	private String country;

    .... getterAndsetter

}

 

 

------------------------------------分割线-------------------------------------

mapper跟model咱们都写好了,下面咱们配置一下数据库链接等配置,此次咱们使用 properties进行配置,如下下是配置内容(这些内容,你们确定都知道了,就不在写注释了),默认使用的数据库链接池是:

org.apache.tomcat.jdbc.pool.DataSource

 

spring.datasource.url = jdbc:mysql://localhost:3306/springboot
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
//若是想替换其余的数据库链接池,增长下面配置就能够了
#spring.datasource.type= 数据库链接池的包路径

 

 

 

由于个人mapper没有在默认的包下,而是在其余的包下,因此,我这还须要在Applicaction的启动类上加上@MapperScan注解,代码以下:

 

@SpringBootApplication
@MapperScan(basePackages = "com.demo.mybatisDemo")
public class DemoApplication{

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

 

以上基本是全部配置了,下面咱们写个单元测试来进行测试下吧:

 

测试代码以下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MybatisTest {

	@Autowired
	private CityMapper cityMapper;

	private Gson gson = new Gson();

	@Test
	public void mybatisMethod(){
		City cn = cityMapper.findByState("CA");

		System.out.println(gson.toJson(cn));
	}

}

 

 

而后你会发现执行成功了,表示配置成功了,这是简单的集成mybatis例子,各位能够参考这个本身进行配置

 

如下是官方的例子,若是有兴趣的同窗,能够经过链接本身查看一下

PS:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 

到这,文章就结束了!

以上,均为本人测试而得出的结果,可能会有出入,或者错误,欢迎指正

欢迎转载,请注明出处跟做者,谢谢!

相关文章
相关标签/搜索