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.
MyBatis springboot gradle 开发配置_第1张图片

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

你可能感兴趣的:(Java)