In the previous article we briefly explained the integration of spring and mybatis, but it is not difficult to find that it is cumbersome to configure. The most obvious point is that we need to write a long SQL Note on our custom mapper interface and register it manually with the spring container. This paper mainly explains the simplified method.
First, the interface is defined, but you don't see any traces of the frame,
Package Org.chen.mybatis.mapper;import Org.chen.domain.spitter;public interface Spittermapper {spitter GetSpitter ( String email);}
If you are using MAVEN, in the Resource folder Resouces, build and org.chen.mybatis.mapper the same directory structure,
The name of the file Spittermapper must be the same as the interface above. The contents of Spittermapper are as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" ><mapper namespace= "Org.chen.mybatis.mapper.SpitterMapper" > <select id= "Getspitter" resulttype= " Org.chen.domain.Spitter "> select * from spitter where email = #{email} </select></mapper>
The ID and interface correspond to the same name of the method name, Resulttype is the return class name. (You might think it's a hassle to write such a long name, it's really, it's a simplified method)
Next in the spring configuration file,
<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "Basepackage" value= "Org.chen.mybatis.mapper"/> </bean>
The function of this bean is the same as automatic detection, which is to automatically register the mapper under the basepackage specified in the package as MyBatis.
To simplify the writing of the Resulttype above,
<bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= " DataSource "ref=" DataSource "/> <property name=" typealiasespackage "value=" Org.chen.domain "/> </bean>
Add a typealiasespackage, that is, the name of the package alias, so directly write resulttype= "Spitter" is OK.
Finally we inject mapper into the service,
@Servicepublic class Testservice {@Autowiredprivate spittermapper spittermapper;public void Setspittermapper ( Spittermapper spittermapper) {this.spittermapper = Spittermapper;}
Spring: Conquer Database (iii)