MyBatis Application Development (4) Application Development Way API Way

Source: Internet
Author: User

1.1. API mode

1.1.1. Development Steps

goal : use MyBatis to query All records of the T_person table from the database.

MyBatis can also use the direct API To configure mappings between records in a database and Java objects, as well as various other required configurations. You no longer need to use any XML configuration file at this time. Because the API is used to establish a mapping relationship,theMapper interface does not need to add any annotations.

Use The steps to develop a database application in the MyBatis API Way are as follows:

(1) Write POJO class Person .

(2) Write Mapper Interface Personmapper .

(3) writing a business interface Personservice .

(4) Writing a Business implementation class Personserviceimpl .

(5) Write MyBatis The overall configuration code.

(6) Write log4j the configuration file log4j.properties .

(7) Writing unit Test classes personservicetest .

to save space, this article lists only the The code and the steps in the way that the XML is different from how it is annotated, the code and the steps that are not listed, refer to the XML method and the description of the annotation method.

1.1.2. Writing the Mapper interface
/*** @Title: personmapper.java* @Package com.test.mybatis3.mapper* @Description:*@author http://www.cnblogs.com/coe2coe/* @date April 9, 2017 pm 4:00:52*@versionV1.0*/ PackageCom.test.mybatis3.mapper;Importjava.util.List;ImportCom.test.mybatis3.pojo.Person;/*** @ClassName: Personmapper Mapper interface * @Description:*@author http://www.cnblogs.com/coe2coe/* @date April 9, 2017 pm 4:00:52**/ Public InterfacePersonmapper {/*** All records are queried. * API mode is used, no mapper configuration files are required, and no mybatis annotations are required. * The mapping relationship between the Findallpersons () method and the SQL statement is established using the MyBatis API in the unit test code. * @return * @throwsException*/List<Person> findallpersons ()throwsException;} 

1.1.3. Writing unit tests

because you are no longer using Sqlmapconfig.xml and personmapper.xml These configuration files, you need to write code to build A running environment that contains the configuration required by MyBatis. You also need to write code to establish a mapping relationship between the Mapper interface and the SQL statement.

/*** @Title: personservicetest.java* @Package com.test.mybatis3.test* @Description:*@author http://www.cnblogs.com/coe2coe/* @date April 9, 2017 pm 4:07:06*@versionV1.0*/ Packagecom.test.mybatis3.test;Importjava.util.ArrayList;Importjava.util.List;ImportJavax.sql.DataSource;ImportOrg.apache.ibatis.builder.StaticSqlSource;ImportOrg.apache.ibatis.datasource.pooled.PooledDataSource;Importorg.apache.ibatis.mapping.Environment;Importorg.apache.ibatis.mapping.MappedStatement;ImportOrg.apache.ibatis.mapping.ResultMap;Importorg.apache.ibatis.mapping.ResultMapping;ImportOrg.apache.ibatis.mapping.SqlCommandType;ImportOrg.apache.ibatis.mapping.SqlSource;Importorg.apache.ibatis.session.Configuration;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;Importorg.apache.ibatis.transaction.TransactionFactory;Importorg.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;Importorg.junit.Test;ImportCom.test.mybatis3.pojo.Person;/*** @ClassName: personservicetest* @Description:*@author http://www.cnblogs.com/coe2coe/* @date April 9, 2017 pm 4:07:06**/ Public classPersonservicetest {/*** Fully use MyBatis's API functions to query the data. * @throwsException*/@Test Public voidTestfindallpersonsbyapi ()throwsException{system.out.println ("By API"); //parameters of the JDBC data sourceString Driver= "Com.mysql.jdbc.Driver"; String URL= "Jdbc:mysql://localhost:3306/mybatis"; String username= "Test"; String Password= "123456"; //Create a data source of type pooled. DataSource DataSource=NewPooleddatasource (Driver,url,username,password);//creating the JDBC transaction managertransactionfactory transactionfactory=Newjdbctransactionfactory ();//creates a MyBatis environment environment object. Environment Environment=NewEnvironment ("Development", Transactionfactory, DataSource); //creates an overall configuration object for the MyBatis. Configuration Configuration=NewConfiguration (environment);//creates a Creator object for the query statement. String Statementid= "Com.test.mybatis3.mapper.PersonMapper.findAllPersons"; String SQL= "SELECT * from T_person ORDER by ID ASC"; Sqlsource Sqlsource=Newstaticsqlsource (configuration, SQL); Mappedstatement.builder Builder=NewMappedstatement.builder (configuration,statementid,sqlsource,sqlcommandtype.select);//creates a mapping object for the result set. String Mapperid= ""; List<ResultMap> Resultmaps =NewArraylist<resultmap>(); List<ResultMapping> resultmappings =NewArraylist<resultmapping>(); Resultmap Resultmap=NewResultmap.builder (Configuration,mapperid,//any string is possible. Person .class,//Resulttype: The Java type of the element in the result set. resultmappings//resultmap: Is empty. ). Build (); Resultmaps.add (RESULTMAP); Builder.resultmaps (Resultmaps); //creates a SELECT statement object. mappedstatement Ms=builder.build ();//Add a statement map to the MyBatis configuration. configuration.addmappedstatement (MS); //constructs a MyBatis sessionfactory object.sqlsessionfactory Sessionbuilder=NewSqlsessionfactorybuilder (). Build (configuration);//will point to the session object instance of MyBatis. sqlsession Session=NULL;Try{//Open session. Session=sessionbuilder.opensession ();//Call Sqlsession's SelectList () method directly to query the result set. //the argument to the SelectList () method is the identifier of a statement. List<Person> persons =session.selectlist (statementid);//output Query results.  for(person person:persons) {System.out.println (person);}}Catch(Exception ex) {ex.printstacktrace ();Throwex;}finally{//make sure the Session object is closed. if(NULL!=session) {Session.close (); session=NULL;}} }} 

The results of the operation are as follows:

by API

0 [main] DEBUG com.test.mybatis3.mapper.PersonMapper.findAllPersons-==> preparing:select * from T_person Order by ID ASC

[Main] DEBUG com.test.mybatis3.mapper.PersonMapper.findAllPersons-==> Parameters:

[Main] DEBUG com.test.mybatis3.mapper.PersonMapper.findAllPersons-<== total:2

person [Id=lisi, Name=li si, status=0]

person [Id=zhangsan, Name=zhang san, status=0]

MyBatis Application Development (4) Application Development Way API Way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.