MyBatis springboot gradle 开发配置

Spring 4 + MyBatis 3 Example with MapperScan and SqlSessionFactoryBean

By Arvind Rai,  March 23, 2015
In this page we will provide Spring 4 and MyBatis 3 Example with MapperScan and SqlSessionFactoryBean. MyBatis provides their API for Spring integration. MyBatis MapperScan annotation scans all mapper interfaces for the given package and makes it available to the spring configuration class. MyBatis implements the mapper interfaces and performs mapper injection in spring implementation classes. We create a bean of MyBatis SqlSessionFactoryBean which provides SqlSession. For transaction management MyBatis uses spring's DataSourceTransactionManager. We need to create a bean of DataSourceTransactionManager in spring configuration class. Transaction is saved by spring MyBatis API and if any error, transactions is roll backed. Here in this page, we will provide a complete example for spring MyBatis integration step by step.

Software Required to Run Example

We are using below software and tool to run our demo. 
1. Java 7 
2. Eclipse 
3. Gradle 
4. MySQL

Table Schema

Find the table which we are using in our demo project. 
Table: village
CREATE TABLE `village` (
	`id` INT(10) NOT NULL,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	`district` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 

Project Structure in Eclipse

Find the screen shot of our project structure in eclipse.
Spring 4 + MyBatis 3 Example with MapperScan and SqlSessionFactoryBean

Gradle File

We are using gradle build in our demo project. 
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter-jdbc:1.2.2.RELEASE'
    compile 'org.mybatis:mybatis-spring:1.2.2'
    compile 'org.mybatis:mybatis:3.2.8'
    compile 'mysql:mysql-connector-java:5.1.34'
    compile 'commons-dbcp:commons-dbcp:1.4'
}  

Create Spring Configuration Class using SqlSessionFactoryBean and MapperScan

We will create a spring configuration class for bean definition. To access mapper interfaces, MyBatis provides MapperScan annotation which will scan mapper interfaces. In mapper interfaces we define our SQL queries. 

MapperScan : Scans the mapper interfaces for MyBatis. MapperScan annotation is used when we are using spring configuration class for bean definition. 
SqlSessionFactoryBean : Provides SqlSesion used by MyBatis. 
DataSourceTransactionManager : For transaction management MyBatis uses spring's DataSourceTransactionManager. 

In DataSource bean, we perform database configurations which is used by SqlSessionFactoryBean and DataSourceTransactionManager bean. Find the configuration class now. 
AppConfig.java
package com.concretepage;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
@MapperScan("com.concretepage.mapper")
public class AppConfig {
	    @Bean
	    public DataSource getDataSource() {
	       BasicDataSource dataSource = new BasicDataSource();
	       dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	       dataSource.setUrl("jdbc:mysql://localhost:3306/concretepage");
	       dataSource.setUsername("root");
	       dataSource.setPassword("");
	       return dataSource;
	   }
	   @Bean
	   public DataSourceTransactionManager transactionManager() {
	       return new DataSourceTransactionManager(getDataSource());
	   }
	   @Bean
	   public SqlSessionFactory sqlSessionFactory() throws Exception {
	      SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
	      sessionFactory.setDataSource(getDataSource());
	      return sessionFactory.getObject();
	   }
} 

Create Mapper Interface

Find the sample mapper interface in which we have created a method to save data in database. 
VillageMapper.java
package com.concretepage.mapper;
import org.apache.ibatis.annotations.Insert;
import com.concretepage.Village;
public interface VillageMapper {
  @Insert("INSERT into village(id,name,district) VALUES(#{vid}, #{villageName}, #{district})")
  void insertVillage(Village village);
} 

POJO for MyBatis

Find the POJO which will be used by MyBatis. 
Village.java
package com.concretepage;
public class Village {
	private Integer vid;
	private String villageName;
	private String district;
	public Integer getVid() {
		return vid;
	}
	public void setVid(Integer vid) {
		this.vid = vid;
	}
	public String getVillageName() {
		return villageName;
	}
	public void setVillageName(String villageName) {
		this.villageName = villageName;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
} 

Run Application

Now we will test our application. 
RunApplication.java
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.mapper.VillageMapper;
public class RunApplication {
	public static void main(String[] args) {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   ctx.register(AppConfig.class);
	   ctx.refresh();
	   VillageMapper mapper = ctx.getBean(VillageMapper.class);	
	   Village village = new Village();
	   village.setVid(1);
	   village.setVillageName("Dhananjaypur");
	   village.setDistrict("Varanasi");
	   mapper.insertVillage(village);
           System.out.println("---Data saved---");
	}
} 
For output, check the database table. We will get our inserted data as below.
Spring 4 + MyBatis 3 Example with MapperScan and SqlSessionFactoryBean


原文位置http://www.concretepage.com/spring-4/spring-4-mybatis-3-example-with-mapperscan-and-sqlsessionfactorybean

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值