mybatis mapper代理方法开发dao

xiaoxiao2021-03-01  14

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时

转载请注明原文地址: https://www.6miu.com/read-4050118.html

最新回复(0)