mybatis学习总结:mybatis和spring, spring boot的集成

简介

  在前面的讨论里已经提到了mybatis的各种配置和操作。从原生的使用角度来看,其实还是有点繁琐的,因为要配置数据源、指定配置文件,设定mapper文件以及接口。在实际的应用中,单纯使用mybatis的机会并不多,它更多的是和spring结合起来用。这里,我们就结合具体的示例讨论详细的配置过程。

 

和spring的集成

  mybatis和spring的集成需要额外加入一些依赖的库,重点是mybatis-spring这个库。详细的依赖库定义如下:

 


	4.0.0

	com.yunzero
	mybatisspring
	0.0.1-SNAPSHOT
	jar

	mybatisspring
	http://maven.apache.org

	
		UTF-8
		1.7.5
		1.2.17
	

	
		
			org.mybatis
			mybatis
			3.4.2
		
		
			org.mybatis
			mybatis-spring
			1.3.1
		
		
			org.springframework
			spring-context
			4.3.6.RELEASE
		
		
			org.springframework
			spring-context-support
			4.3.6.RELEASE
			
				
					commons-logging
					commons-logging
				
			
		
		
			org.springframework
			spring-jdbc
			4.3.6.RELEASE
		
		
			org.springframework
			spring-test
			4.3.6.RELEASE
		
		
			org.aspectj
			aspectjrt
			1.8.10
		
		
			org.aspectj
			aspectjweaver
			1.8.10
		
		
			cglib
			cglib-nodep
			3.2.4
		
		
			org.apache.commons
			commons-dbcp2
			2.1.1
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			jcl-over-slf4j
			${slf4j.version}
			runtime
		
		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
			runtime
		

		
			log4j
			log4j
			${log4j.version}
			runtime
		
		
			mysql
			mysql-connector-java
			5.1.40
		
		
			junit
			junit
			4.12
			test
		
	
	
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.6.0
				
					1.8
					1.8
					${project.build.sourceEncoding}
				
			
		
	

 

  这里引用的库比较多,其中spring相关的主要是应用中需要使用到的对于事物以及依赖注入等相关特性。

  在配置好基本的依赖之后,下一步就是要配置相关的bean了,这里一般都放在applicationContext.xml文件里。详细的配置如下:

 

 




    
    
    

    
    
    
    
    
        
        
        
        
    
    
    
        
        
        
        
    

    
        
    
    
    
        
    
    
    
    

  这里有不少的配置信息,前面几个是定义了依赖注入支持的方式,对于mybatis来说,重点在于

   这部分指定了mybatis里mapper接口定义所放的地方。这样以后所有的mapper接口都放到这个指定的包下面就可以。在下面接着定义的sqlSession,sqlSessionFactory这两个bean就相当于配置好了对应数据源和对应在spring里怎么使用sqlSession的模板。

  下面的transactionManager主要用来设定业务逻辑层里对事物的支持。

 

  基本上把上面那些东西给配好,差不多就完成了。剩下的就是对应的mapper配置文件了。以StudentMapper为例,它的配置和前面的配置一样:



  

	
	
	
  		
		
		
		
		
		
  	
  	
  	
		
		
		
		
	
	
	

  mapper文件主要起到一个定义对象和数据库字段映射的作用。剩下的mapper接口部分也很类似,比如AddressMapper:

public interface AddressMapper {
	@Select("select addr_id as addrId, street, city, state, zip, country from ADDRESSES where addr_id=#{id}")
	Address selectAddressById(int id);

	@Insert("insert into ADDRESSES(street, city, state, zip, country) values(#{street},#{city},#{state},#{zip},#{country})")
	int insertAddress(Address address);
}

  在设置好上述内容之后,还有一个重要的东西就是对定义service层,对mapper的访问进行封装。在之前的示例里,我们都是通过使用sqlSession来封装mapper,这里因为有了前面的定义,这一部分相当于被mybatis-spring封装起来了。它的实现则更加简单:

@Service
@Transactional
public class StudentService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private StudentMapper studentMapper;
	
	@Autowired
	private AddressMapper addressMapper;
	
	public List findAllStudents() {
		return studentMapper.findAllStudents();
	}
	
	public Student findStudentById(Integer id) {
		logger.debug("findStudentById :"+id);
		return studentMapper.findStudentById(id);		
	}

	public Student findStudentWithAddressById(int id) {
		return studentMapper.selectStudentWithAddress(id);		
	}
	
	public Student createStudent(Student student) {
		Address address = student.getAddress();
		if(address != null){
			addressMapper.insertAddress(address);
		}
		if(student.getName()==null || student.getName().trim().length()==0){
			throw new RuntimeException("Student Name should not be null");
		}
		studentMapper.insertStudent(student);
		return student;
	}
	// some code emitted...
}

   在这个示例里,我们只是直接注入StudentMapper和AddressMapper就可以了。在实际的方法实现里,一般只是对于数据的更新或者删除等操作才使用事物。我们可以将类上面添加的Transactional annotation单独添加到对应的方法上。

  在完成上述的步骤之后,一个具有完整功能的spring加mybatis工程就配置好了。详细的细节可以参照后面所带的附件。

 

和spring boot的集成

  在这些年来,我们在开发中使用spring boot来越来越多。spring boot对约定强于配置的方式支持使得我们开发的过程中省略了很多繁琐的配置。对于很多工程,它也提供了默认的配置,我们只需要做一点少量的修改。那么,如果基于它来和mybatis集成的话,会是怎么样呢?

  我们先看看对应的依赖配置:

 



	4.0.0

	com.yunzero
	springboot-mybatis
	0.0.1-SNAPSHOT
	jar

	mybatisspringboot
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.1.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.2.0
		
        
            com.zaxxer
            HikariCP
        
		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

  这里pom文件的定义反而简单了很多,因为是了spring-boot的模板,它这里有一个spring-boot-starter-parent的父工程,这里就已经将很多东西配置好了。这里配置依赖的mysql-connector等都不需要指定具体的版本号,由spring-boot里的模板事先指定好了,这样可以尽量的避免各种引入的包冲突。

  另外,为了保证数据库连接的性能,这里还额外引入了一个数据库连接池的库HikariCP。 

  在把上述东西配好之后,我们只需要在对应的配置文件里设定几个相关的配置了,在spring-boot里,典型的配置文件就是系统默认生成的application.properties文件。还有一个常用的就是application.yml文件。这里采用yml文件。它的具体配置内容如下:

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://localhost:3306/elearning
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: password

mybatis:
  type-handlers-package: com.yunzero.typehandlers
  type-aliases-package: com.yunzero.domain

  它的配置样式和properties文件差不多,只是在某些情况下表达方式显得灵活一些。因为这里是针对数据库连接池的配置,所以它的datasource.type下面就需要配置上对应的HikariDataSource。当然,针对Hikaricp,它还有一些具体的参数,也可以配置在这里。

  在配置好上述内容之后,剩下的就只要配上对应的mapper文件和mapper接口了。像之前需要配置各种sqlSession, sqlSessionFactory之类的东西都给省了。因为这些spring-boot都已经事先设置好了。其他部分都不需要做任何的修改就可以了。详细的内容也可以参照后续的附件。

 

总结

  总的来说,mybatis和spring,spring boot的集成并不复杂。主要是要注意几个需要配置的地方。

你可能感兴趣的:(java,mybatis,spring)