mybatis mapper代理方法開發dao
阿新 • • 發佈:2018-12-11
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時