spring和mybatis整合02

本文介绍如何在SSM框架中集成MyBatis,并通过配置文件设置Mapper接口及其实现,最后通过JUnit进行单元测试验证功能正确性。

1

2.config/配置文件

config/mybatis/SqlMapConfig.xml

	<!-- 加载映射文件 -->
	<mappers>		
		<package name="com.app.ssm.mapper" />
	</mappers>


config/spring/applicationContext.xml

	<!-- Mapper包实现类 -->
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.app.ssm.mapper.UserMapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>


3.src/ssm包

mapper接口

public interface UserMapper {
	
	// R  根据id查询用户信息
	public User findUserById(int id) throws Exception;

}


mapper.xml

<?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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="com.app.ssm.mapper.UserMapper">

	<!-- R  根据id查询一条记录结果 -->
	<select id="findUserById" parameterType="int" resultType="user">
		SELECT * FROM USER WHERE id=#{value}
	</select>
		
</mapper>


4.test单元测试

package com.app.ssm.mapper;  

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.ssm.po.User;

/** 
 *@Title UserMapperTest.java 
 *@description TODO 
 *@time 2016年9月13日 下午3:49:43 
 *@author wyz 
 *@version 1.0 
 **/
public class UserMapperTest {
	
	private ApplicationContext applicationContext;

	@Before
	public void setUp() throws Exception {
		applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
	}

	@Test
	public void testFindUserById() throws Exception{
		UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
		User user = userMapper.findUserById(1);
		System.out.println(user);
	}

}


5

6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值