spring和mybatis整合02

来源:互联网 发布:网站流量数据分析 编辑:程序博客网 时间:2024/05/18 21:07

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 mapperPUBLIC "-//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;@Beforepublic void setUp() throws Exception {applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic void testFindUserById() throws Exception{UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");User user = userMapper.findUserById(1);System.out.println(user);}}


5

6

0 0
原创粉丝点击