mybatis mapper代理方法开发dao

UserMapper.xml中namespace的值要与mapper.java的完全限定地址一样

<?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="zzu.qg.mybatis.dao.UserMapper">
	<select id="findUserById" parameterType="int" resultType="zzu.qg.mybatis.entity.User">
		select * from [user] where id=#{value}
	</select>
	
	<insert id="insertUser" parameterType="zzu.qg.mybatis.entity.User">
		insert into [user] values(#{userName},#{password},#{sex},#{birthday})
	</insert>
</mapper>

UserMapper.java  方法名,,输入参数类型,,返回值类型

public interface UserMapper {
	
	public User findUserById(int id);
	
	public void insertUser(User user);
	
}

测试类

public class TestUserDao {
	
	
	private SqlSessionFactory sqlSessionFactory;
	private InputStream inputStream;
	@Before
	public void initSqlSessionFactory(){
		String resource="config/mybatis/mybatis-config.xml";
		try {
			inputStream = Resources.getResourceAsStream(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
	}
	
	@Test
	public void testFindUserById(){
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//将mapper接口的字节码对象当作参数传给sqlSession.getMapper(),sqlSession自动创建mapper接口的代理对象
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		User user=userMapper.findUserById(1);
		System.out.println(user);
		sqlSession.close();
	}
	
	@Test
	public void testInsertUser(){
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//将mapper接口的字节码对象当作参数传给sqlSession.getMapper(),sqlSession自动创建mapper接口的代理对象
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		User user=new User("张三","suibianle","女","2000-9-23");
		userMapper.insertUser(user);
		sqlSession.commit();
		System.out.println(user.getId());
		
		sqlSession.close();
	}
}

定义完mapper映射文件后,接下来就要开发mapper接口,编写mapper接口需要遵循以下四个基本规范:

1、在mapper.xml中namespace的值等于mapper接口的完全限定地址

2、mapper.java中的方法名要与mapper.xml的statement的id一致

3、mapper.java中的方法输入参数类型要与mapper.xml的parameterType的类型一致

4、mapper.java中的返回值类型要与mapper.xml的resultType的类型一致(注意:resultType指的是返回单个结果的类型)

执行结果:

执行testFindUserById时

执行insertUser时

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值