Er dynamic proxy in the Mybatis framework, mybatismapper

Source: Internet
Author: User

Er dynamic proxy in the Mybatis framework, mybatismapper

Development specifications:

To develop the mapper interface, you only need to compile the mapper interface (equivalent to the Dao interface ),
The Mybatis framework creates dynamic proxy objects for interfaces according to interface definitions,
The method body of the proxy object is the same as that of the Dao interface implementation class method.

Mapper interface development must follow the following specifications:
1. The namespace in the Mapper. xml file is the same as the mapper interface path.
2. The Mapper interface method is the same as the id of each statement defined in Mapper. xml.
3. The input parameter type of the Mapper interface method is the same as the parameterType type of each SQL statement defined in mapper. xml.
4. The output parameter type of the Mapper interface method is the same as the resultType of each SQL statement defined in mapper. xml.

1. Create a project and export the package:

Ii. 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 {/** original method to obtain the 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 static method for database operation to get session */public static SqlSession getSqlSession () throws IOException {String config = "mybatis-config.xml"; InputStream configStream = Resources. getResourceAsStream (config); SqlSessionFactoryBuilder buider = new SqlSessionFactoryBuilder (); SqlSessionFactory = buider. build (configStream); SqlSession session = factory. openSession (); return session ;}}

2. Set up mybatis-config.xml files

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 a beans class:

Package com. zsq. beans; import java. util. date;/** javaBean class: */public class MyInfo {private int id; private String myname; private 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 age) {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 age, 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 class attributes, attribute names, and table Field Types and Field Names correspond one to one:

4. Write the xml file of the SQL statement

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. zsq. mapper. MyInfoMapper "> <! -- Insert a row of data --> <insert id = "insert1"> insert into myinfo (id, myname, sex, age, email, address, brith) values (default, 'yang Yunfei ', 'male', 26, '2017 @ qq.com', 'henan ', '2017-5-6') </insert> <! -- Query by id --> <select id = "selectById" parameterType = "Integer" resultType = "com. zsq. beans. myInfo "> select * from myinfo where id =#{ id} </select> <! -- Full query --> <select id = "selectAll" resultType = "com. zsq. beans. MyInfo"> select * from myinfo order by id desc </select> <! -- Fuzzy query by name --> <select id = "findMyName" parameterType = "String" resultType = "com. zsq. beans. myInfo "> select * from MyInfo where myname like" % "# {haha}" % "</select> <! -- Update the Department field content by id --> <update id = "updateById" parameterType = "int"> update myinfo set age = 99 where id =#{ id} </update> <! -- Modify information by address --> <update id = "updateById2" parameterType = "String"> update myinfo set id = 7, myname = "Zeng Zhiwei" where address =#{ address} </update> <! -- Upload an object based on the id and new parameters --> <update id = "updayeMyInfoById" parameterType = "com. zsq. beans. myInfo "> update myinfo set myname =#{ myname}, age =#{ age}, sex =#{ sex}, email =#{ email }, address = # {address}, brith = # {brith} where id = # {id} </update> <! -- Delete a user by id --> <delete id = "delById" 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 interfaces. The implementation class generates public interface MyInfoMapper from the dynamic proxy {/** key: four principles must be followed * 1> method name = myInfo. id in xml * 2> return value type and MyIndoMapper. the return value type in the xml file must be consistent * 3> the input parameter type of the method must be different from that of MyInfoMapper. the input parameters in xml are of the same type. * 4> bind the namespace to this interface * // insert a row of data and the content is written to the dead public int insert1 (); // The id-based Query Method public MyInfo selectById (int id); // The full query method public List <MyInfo> selectAll (); // The method for fuzzy query based on myname public MyInfo findMyName (String myname); // The method for updating the content of the Department field based on id public int updateById (int id ); // The address-based modification method public int updateById2 (String address); // The method for passing an object based on id and new parameters public int updayeMyInfoById (MyInfo user ); // Delete the user's id-based deletion method 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 {// obtain sessionSqlSession session = Utils. getSqlSession ();/** 1> session helps me generate an implementation class ** 2> return or interface, and then call the Method */MyInfoMapper info = session. getMapper (MyInfoMapper. class);/* Insert a row of Data int I = info. insert1 (); System. out. println (I); * // * query MyInfo selectById = info by id. selectById (5); System. out. println (selectById); * // * Full query List <MyInfo> all = info. selectAll (); for (MyInfo myInfo: all) {System. out. println (myInfo);} * // * fuzzy query MyInfo info2 = info by name. findMyName ("Cloud"); System. out. println (info2); System. out. println (info2.getMyname (); * // * update the content of the Department field according to the id. int id = info. updateById (3333); System. out. println (id); * // * Set int id2 = info according to the address. updateById2 ("Lianhua township"); System. out. println (id2); * // * upload an object MyInfo user = new MyInfo (); user based on the id and new parameters. setId (3350); user. setMyname ("Zeng Zhiwei"); user. setSex ("female"); user. setAge (2323); user. setEmail ("789789789@qq.com"); user. setAddress ("Xicheng"); user. setBrith (new Date (); int t1 = info. updayeMyInfoById (user); System. out. println (t1); * // Delete the int t1 = info. delById (3353); System. out. println (t1); // delete a session whose id is 3353. commit (); session. close ();}}

  

  

 

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.