Mapper interface development method only requires programmers to write the Mapper interface (equivalent to Dao interface), the MyBatis framework creates an interface based on the interface definition of the dynamic proxy object, the proxy object's method body with the upper Dao Interface Implementation class method.
Mapper interface Development is subject to the following specifications:
1. The namespace in the Mapper.xml file is the same as the classpath of the Mapper interface.
2. the Mapper interface method name is the same as the ID of each statement defined in the mapper.xml
3. The input parameter type of the Mapper interface method and the parametertype of each SQL defined in mapper.xml the same type
4. The output parameter type of the Mapper interface method and the resulttype of each SQL defined in Mapper.xml The same type
mapper.xml ( map file )
Define mapper mapping file usermapper.xml(content same as Users.xml), need to modify The value of namespace is the usermapper interface path. Place the usermapper.xml under the mapper directory under classpath .
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><Mappernamespace= "Cn.itcast.mybatis.mapper.UserMapper"><!--get user information by ID - <SelectID= "Finduserbyid"ParameterType= "int"Resulttype= "Cn.itcast.mybatis.po.User">SELECT * from user where id = #{id}</Select><!--Custom Criteria Query user list - <SelectID= "Finduserbyusername"ParameterType= "Java.lang.String"Resulttype= "Cn.itcast.mybatis.po.User">SELECT * from user where username like '%${value}% '</Select><!--Add User - <InsertID= "Insertuser"ParameterType= "Cn.itcast.mybatis.po.User"> <SelectkeyKeyproperty= "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 ( interface file )
/*** User Management mapper*/ PublicInterfaceUsermapper {//query user information based on user ID PublicUser Finduserbyid (intIdthrowsException; //querying the user list PublicList<user> Finduserbyusername (String username)throwsException; //Add user Information Public voidInsertuser (user user)throwsException;}
Use
Gets the proxy object for the mapper interface
Usermapper usermapper = Session.getmapper (usermapper. Class);
Gets the proxy object after calling its method to complete the business
Mapper Dynamic Proxy Mode