mabatis mapper开发规范
定义一个mapper接口
package mapper; import pojo.User; public interface UserMapper { public User getUser(int id) throws Exception; public void insertUser(User user) throws Exception; }
定义一个UserMapper.xml指向它,注意namespace需要指向它的全路径,sql语句id同方法名,然后入参和结果都和方法入参,返回一致。
xml名称不一定要和接口名相同,它是通过namespace搜索的。
<?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="mapper.UserMapper"> <select id="getUser" parameterType="int" resultType="User"> select id, name, age, gmt_create gmtCreate from users where id=#{id} </select> <insert id="insertUser" parameterType="User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> insert into users(name, age, gmt_create, money) VALUE ('xiao', 24, '1991-06-26', 10000) </insert>
测试
private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception{ sqlSessionFactory = MybatisUtils.getFactory(); } @Test public void testGetUser() throws Exception{ SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUser(1); System.out.println(user); }
通过sqlSession.getMapper返回代理类。
根据返回的参数智能选择使用selectOne或selectList,即程序员可以定义
public User getUser(int id) throws Exception;
public List<User> getUserByName(String userName) throws Exception;