Today, we use the SqlSessionTemplate persistence template to integrate spring and mybatis. In fact, the difference is that we can modify the spring configuration file and change the test class as follows:
This is the main content of the spring control file. Note that you should not forget to inject sqlsession into the test class.
[Html]
<Span style = "font-size: 14px;"> <! -- Create a jdbc data source -->
<Bean id = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource" destroy-method = "close">
<Property name = "driverClassName" value = "oracle. jdbc. driver. OracleDriver"/>
<Property name = "url" value = "jdbc: oracle: *****: ******: 1521: *****"/>
<Property name = "username" value = "*****"/>
<Property name = "password" value = "*****"/>
</Bean>
<Bean id = "sqlSessionFactory" class = "org. mybatis. spring. SqlSessionFactoryBean">
<Property name = "dataSource" ref = "dataSource"/>
<Property name = "configLocation" value = "classpath: com/Template/configuration. xml"/>
</Bean>
<Bean id = "sqlSession" class = "org. mybatis. spring. SqlSessionTemplate">
<Constructor-arg index = "0" ref = "sqlSessionFactory"/>
</Bean>
<Bean id = "customerTest" class = "com. Template. Test">
<Property name = "sqlSession" ref = "sqlSession"/>
</Bean> </span>
This is a test class. Because this is SqlSessionTemplate, it does not need to be inherited.
[Java]
<Span style = "font-size: 14px;"> import javax. annotation. Resource;
Import org. mybatis. spring. SqlSessionTemplate;
Import org. springframework. beans. factory. BeanFactory;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Public class Test {
@ Resource
Public SqlSessionTemplate sqlSession;
Public static void main (String [] args ){
// TODO Auto-generated method stub
New Test (). firstTest ();
}
Public void setSqlSession (SqlSessionTemplate sqlSession ){
This. sqlSession = sqlSession;
}
Public void firstTest (){
BeanFactory factory = new ClassPathXmlApplicationContext ("com/Template/applicationContext. xml ");
Test test = (Test) factory. getBean ("customerTest ");
Customer cus = (Customer) test. sqlSession. selectOne ("selectCustomer", 10696 );
System. out. println (cus );
}
} </Span>
Summary: The difference between an abstract class and a template is that SqlSessionTemplate does not need to be inherited in the test class. Therefore, you need to manually write the setter method to pass the value when passing the value, while the abstract class is inherited, so the value is automatically assigned. When manually assigning values, note that <property name = "sqlSession" ref = "sqlSession"/> the name here is the property name, when writing the setter method, you can refer to it, so the setter method is easy to name.