標籤:space 對應檔 mybatis 編寫 except value throw utf-8 birt
Mapper介面開發方法只需要程式員編寫Mapper介面(相當於Dao介面),由Mybatis架構根據介面定義建立介面的動態代理對象,代理對象的方法體同上邊Dao介面實作類別方法。
Mapper介面開發需要遵循以下規範:
1、 Mapper.xml檔案中的namespace與mapper介面的類路徑相同。
2、 Mapper介面方法名和Mapper.xml中定義的每個statement的id相同
3、 Mapper介面方法的輸入參數類型和mapper.xml中定義的每個sql 的parameterType的類型相同
4、 Mapper介面方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同
Mapper.xml(對應檔)
定義mapper對應檔UserMapper.xml(內容同Users.xml),需要修改namespace的值為 UserMapper介面路徑。將UserMapper.xml放在classpath 下mapper目錄 下。
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><!-- 根據id擷取使用者資訊 --> <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User"> select * from user where id = #{id} </select><!-- 自訂條件查詢使用者列表 --> <select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User"> select * from user where username like ‘%${value}%‘ </select><!-- 添加使用者 --> <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> select LAST_INSERT_ID() </selectKey> insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) </insert></mapper>
Mapper.java(介面檔案)
/** * 使用者管理mapper */Public interface UserMapper { //根據使用者id查詢使用者資訊 public User findUserById(int id) throws Exception; //查詢使用者列表 public List<User> findUserByUsername(String username) throws Exception; //添加使用者資訊 public void insertUser(User user)throws Exception; }
使用
//擷取mapper介面的代理對象
UserMapper userMapper = session.getMapper(UserMapper.class);
擷取代理對象後調用其方法完成業務
Mapper 動態代理方式