Mapper dynamic proxy mode in MyBatis framework

Source: Internet
Author: User

Development specification:

Mapper interface development method only need to program ape to write Mapper interface (equivalent to DAO interface),
Dynamic proxy objects that are created by the MyBatis framework based on the interface definition.
The method body of the proxy object is the same as the DAO interface implementation class method.

Mapper interface development is subject to the following specifications:
The namespace in the 1.mapper.xml file is the same as the path to the Mapper interface.
The 2.Mapper interface method is the same as the ID of each statement defined in Mapper.xml.
The input parameter type of the 3.Mapper interface method is the same as the type of parametertype for each SQL defined in Mapper.xml.
The output parameter type of the 4.Mapper interface method is the same as the type of resulttype for each SQL defined in Mapper.xml.

First, create the project and guide the package:

Second, the code implementation:

1. Create a tool class:

Package Com.zsq.utils;import Java.io.ioexception;import Java.io.inputstream;import java.sql.connection;import Java.sql.drivermanager;import Java.sql.sqlexception;import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public class Utils {/* * Raw Method gets database connection object */public static Connection Getconnection () throws SQLException, classnotfoundexception{string driver = "Com.mysql.jdbc.Driver"; String url = "Jdbc:mysql://localhost:3306/zengsiqi"; String username = "root"; String userpass = "123456"; Class.forName (driver); Connection con = drivermanager.getconnection (URL, username, userpass); return con;} /* * MyBatis operation database Gets the static method of session */public static Sqlsession getsqlsession () throws ioexception{string config = "Mybatis-co Nfig.xml "; InputStream configstream = resources.getresourceasstream (config); Sqlsessionfactorybuilder Buider = new Sqlsessionfactorybuilder (); SqlsessionfActory factory = Buider.build (Configstream); sqlsession session = Factory.opensession (); return session;}}

2. Build Mybatis-config.xml File

Copy Code

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--<properties resource= "db.properties"/>--><environments default= " Development "><environment id=" development "><transactionmanager type=" JDBC "/><dataSource type=" Pooled "><property name=" Driver "value=" Com.mysql.jdbc.Driver "/><property name=" url "value=" Jdbc:mysql ://localhost:3306/zengsiqi "/><property name=" username "value=" root "/><property name=" password "value=" 123456 "/></datasource></environment></environments><mappers><mapper resource=" com /zsq/sqlmap/myinfomapper.xml "/></mappers></configuration>

3. Create the Beans class:

Package Com.zsq.beans;import java.util.date;/* * JavaBean class: */public class MyInfo {private int id;private String MYNAME;PR  Ivate string sex;private int age;private string email;private string address;private Date brith;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getmyname () {return myname;} public void Setmyname (String myname) {this.myname = MyName;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} Public Date Getbrith () {return brith;} public void Setbrith (Date brith) {this.brith = Brith;} Public MyInfo () {}public myinfo (int id, string myname, String sex, Int., string email,string address, Date Brith) {This . id = id;this.myname = MynamE;this.sex = Sex;this.age = Age;this.email = email;this.address = Address;this.brith = Brith;} @Overridepublic String toString () {return "MyInfo [id=" + ID + ", myname=" + MyName + ", sex=" + sex+ ", age=" + Age + ", Email= "+ email +", address= "+ address+", brith= "+ Brith +"] ";}}

Note: The properties of the class, the property name corresponds to the field type of the table, and the field name is one by one:

4. xml file that writes SQL statements

<?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= "Com.zsq.mapper.MyInfoMapper" ><!--inserting a row of data--><insert id= "Insert1" >insert into MyInfo (id,myname,sex,age,email,address,brith) VALUES (default, ' Xu ', ' Male ', ', ', ' [email protected] ', ' Henan ', ' 1992-5-6 ') </insert><!--query--><select id= "Selectbyid" parametertype= "Integer" resulttype= "by ID Com.zsq.beans.MyInfo ">select * from MyInfo where id = #{id}</select><!--full search--><select id=" SelectAll "R Esulttype= "Com.zsq.beans.MyInfo" >select * from MyInfo ORDER by ID desc</select><!--fuzzy query search by name--><sel ECT id= "Findmyname" parametertype= "String" resulttype= "Com.zsq.beans.MyInfo" >select * from MyInfo where myname like " % "#{haha}"% "</select><!--Update Department field contents by ID--><update id=" updatebyid "parametertype=" int ">update MyInfo Set age = id=#{id}</update><!--Modify information based on address--><update id= "updateById2" parametertype= "String" >update myinfo Set id = 7,myname = " Eric Tsang "where address = #{address}</update><!--Pass an object to the new parameter based on the ID--><update id=" Updayemyinfobyid "Parameterty Pe= "Com.zsq.beans.MyInfo" >update myinfo Set myname = #{myname},age = #{age}, sex = #{sex},email = #{email},address = # {address},brith = #{brith} where id = #{id}</update><!--delete user deleted--><delete id= "Delbyid" based on ID parametertype = "int" >delete from MyInfo where id = #{id}</delete></mapper>

5.mapper Interface:

Package Com.zsq.mapper;import Java.util.date;import Java.util.list;import com.zsq.beans.myinfo;//Implement dynamic Proxy: write-only interface  , Implementation class generated by dynamic proxy public interface Myinfomapper {/* *  Focus: must follow four principles *  1> Method name = = Myinfo.xml ID name *2> return value type with Myindomapp The return value type in the Er.xml file is consistent with the type of the *3> method to be the same as the types of the parameters in the Myinfomapper.xml *4> namespace binding This interface *///inserting a row of data  and content is a dead public int insert1 ()///based on the ID query method public myinfo Selectbyid (int id);//Full search method public list<myinfo> SelectAll ();//Fuzzy query  According to MyName method public MyInfo findmyname (String myname);//Update Department field contents by ID public int Updatebyid (int id);//Based on address Method of modifying information public int updateById2 (String address);//  method of passing an object according to ID and new parameter public int Updayemyinfobyid (myinfo user);//delete user  method to delete by ID public int Delbyid (int id);}

6.test class:

Package Com.zsq.test;import Java.util.date;import java.util.list;import org.junit.test;import com.zsq.Utils.Utils; Import Com.zsq.beans.myinfo;import Com.zsq.mapper.myinfomapper;import Org.apache.ibatis.session.sqlsession;public Class Myinfomappertest {@Testpublic void Test1 () throws Exception {//Get sessionsqlsession session = Utils.getsqlsession ()         ;/* * 1>session help me generate an implementation class * 2> returns the interface, and then the method */myinfomapper info = session.getmapper (myinfomapper.class);/* Insert a row of data int i = Info.insert1 (); System.out.println (i); *//* query by id myinfo Selectbyid = Info.selectbyid (5); System.out.println (Selectbyid); *//* full check list<myinfo> all = Info.selectall (); for (MyInfo Myinfo:all) {SYSTEM.O Ut.println (MyInfo);} *//* Fuzzy Query According to the name of MyInfo Info2 = Info.findmyname ("cloud"); System.out.println (Info2); System.out.println (Info2.getmyname ()); *//* Update Department field contents by ID int id = info.updatebyid (3333); SYSTEM.OUT.PRINTLN (ID); *//* modify information according to address int id2 = INFO.UPDATEBYID2 ("Lianhua Township"); System.out.println (ID2); */* Based on ID and new parameters An object MyInfo user = new MyInfo (); User.setid (3350); User.setmyname ("Eric Tsang"); User.setsex ("female"); User.setage (2323); user.se Temail ("[email protected]"); User.setaddress ("Xicheng"); User.setbrith (new Date ()); int T1 = Info.updayemyinfobyid ( user); SYSTEM.OUT.PRINTLN (t1); *///Delete the user by id delete int T1 = Info.delbyid (3353); SYSTEM.OUT.PRINTLN (t1);//id for 3353 delete session.commit (); Session.close ();}}

  

  

Mapper dynamic proxy mode in MyBatis framework

Related Article

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.