一般通过 Mybatis Generator 会生成三种文件:
将 Mybatis 和 Spring 整个方法是:
1. 在 applicationContext.xml 中加入如下内容:
<!-- mybatis 文件配置,创建SqlSessionFactory,同时指定数据源,扫描所有 mapper.xml 文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis.xml" />
<!--
<property name="mapperLocations" value="classpath:mybatis/spark/xml/*.xml" />
-->
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
2. 生成 mybatis.xml 文件:
<<mybatis.xml>>
3. 写 UserService 类,实现 TUserMapper 等需要实现的接口,代码如下:
package cn.spark.service;
import java.util.List;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;
import mybatis.spark.dao.TUserMapper;
import mybatis.spark.pojo.TUser;
@Service
public class UserService implements TUserMapper {
public SqlSessionTemplate sqlSession;
@Resource(name="sqlSession")
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public int deleteByPrimaryKey(String userCode) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insert(TUser record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public TUser selectByPrimaryKey(String userCode) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<TUser> selectAll() {
// TODO Auto-generated method stub
return sqlSession.getMapper(TUserMapper.class).selectAll();
}
@Override
public int updateByPrimaryKey(TUser record) {
// TODO Auto-generated method stub
return 0;
}
}
4. 测试 UserService 类
新建一个 Junit 测试类,测试 UserServie ,如下:
package cn.spark.service;
import static org.junit.Assert.*;
import java.util.List;
import mybatis.spark.pojo.TUser;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.spark.doaimpl.TUserMapperImpl;
public class UserServiceTest {
@Test
public void testSelectAll() {
ApplicationContext cxt = new ClassPathXmlApplicationContext("config/applicationContext.xml");
UserService user = (UserService) cxt.getBean("userService");
List<TUser> users = user.selectAll();
System.out.println( users.size() );
}
}