1. Basic Ideas
You need to write the Mapper interface and the Mapper.xml mapping file. Writing mapper interfaces requires following some development specifications, allowing MyBatis to automatically generate Mapper interface implementation class proxy objects.
A. Namespace equals Mapper interface address in Mapper.xml
The method name in the B.mapper.java interface is consistent with the statement ID in the Mapper.xml
The method input parameter type in the C.mapper.java interface is consistent with the type of parametertype specified in mapper.xml statement
The method return value type in the D.mapper.java interface is the same as the resulttype specified in mapper.xml statement
See below for specific implementations of these 4 steps.
2. Create the following documents:
3. Load Mapper.xml in Sqlmapconfig.xml
<mappers>
<mapper resource= "Sqlmap/user.xml" ></mapper>
<mapper class= "Mapper. Usermapper "/>
</mappers>
4. Write the test file and test the success.
Package mapper;
Import Java.io.InputStream;
Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
Import Org.junit.Before;
Import Org.junit.Test;
Import Po. User;
public class Usermappertest {
Private Sqlsessionfactory sqlsessionfactory;
@Before
public void SetUp () throws Exception {
String resource = "Sqlmapconfig.xml";
InputStream InputStream = resources.getresourceasstream (Resource);
Sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream);
}
@Test
public void Testfinduserbyid () throws Exception {
Sqlsession sqlsession = Sqlsessionfactory.opensession ();
Usermapper usermapper = Sqlsession.getmapper (Usermapper.class);
User user = Usermapper.finduserbyid (1);
SYSTEM.OUT.PRINTLN (user);
}
}
5. Proxy object Internal call SelectOne or SelectList
Although the above is inconsistent, it is still correct, as explained below:
If the Mapper method returns a single Pojo object (not a collection object), the proxy object queries the database internally through SelectOne.
If the Mapper method returns a collection object, the proxy object internally queries the database through SelectList.
6.mapper interface method parameters can only have one effect on system development
In the system framework, the DAO layer code is common to the business layer. Even if the Mapper interface has only one parameter, the Pojo of the wrapper type can be used to meet the needs of different business methods.
Note: The parameters of the persistence layer method can be wrapped type, map, etc., the service method is not recommended to use the wrapper type (not conducive to the scalability of the business layer).
MyBatis Learning 13-mybatis using Mapper Proxy DAO method for development