MyBatis realization of data deletion and modification

Source: Internet
Author: User

MyBatis implementation of data additions and deletions to prepare for the pre-changenew Java Engineering or Java Wweb Project,you need to import the following packages,

The basic work has been done and the next step is to get started. New entity classCreate a new entity class that corresponds to a database table
Package com.edu.hpu.domain;/** * @author Administrator *user table corresponding entity class */public class User {      //Entity class properties and table field name one by one  private int id;  private String name;  private int age;     Encapsulates a property with the public  int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}  Add the ToString Method  @Overridepublic String ToString () {return "User [id=" + ID + ", name=" + name + ", age=" + Age + "]";}}
Add MyBatis Tool classAdd the tool class that you used, as shown below,
Package Com.edu.hpu.util;import Java.io.inputstream;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public Class Mybatisutil {/** * get sqlsessionfactory * @return Sqlsessionfactory */public static SQLSESSIONFAC Tory getsqlsessionfactory () {String resource = "conf.xml";//Pickup profile InputStream is = MyBatisUtil.class.getCl        Assloader (). getResourceAsStream (Resource);        Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (IS);    return factory; }/** * Get sqlsession * @return sqlsession */public static sqlsession getsqlsession () {retur    n Getsqlsessionfactory (). Opensession ();         }/** * Get sqlsession * @param isautocommit * True indicates that the created Sqlsession object will automatically commit the transaction after the SQL is executed * False means that the created Sqlsession object does not commit the transaction automatically after executing the SQL, so we need to manually call Sqlsession.commit () to commit the transaction * @return Sqlsession */    public static Sqlsession Getsqlsession (Boolean isautocommit) {return getsqlsessionfactory (). Opensession (Isauto    Commit); }}

There are two methods for adding and deleting data using MyBatis, which are configuration file operation and annotation operation respectively. Working with a configuration fileThe database configuration file, as shown below, configures the database information,
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >            <configuration> <environments default= "Development" > <environment id= "Development" >                <transactionmanager type= "JDBC"/> <!--Configuring database connection Information--<datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value = "jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8&zerodatetimebehavior= Converttonull "/> <property name=" username "value=" root "/> <property name=" Pass Word "value=" admin "/> </dataSource> </environment> </environments> <map pers> <!--register Usermapper.xml file, Usermapper.xml is located under Com.edu.hpu.mapping This package, so resource written Com/edu/hpu/mapping/usermapper.xml--> <mapper resource= "Com/edu/hpu/mapping/usermapper.xml"/> <!--<mapper class= "Com.edu.hpu.mapping.UserMapper_11"/>-</mappers></configuration>

Configure the Operation database statement file as follows,
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.edu.hpu.mapping.userMapper" > <!--The SQL statement that wrote the query in the Select tab, set the ID property of the Select tag to GetUser, The id attribute value must be unique and cannot be reused using the ParameterType property to indicate the type of parameter used when querying, Resulttype property indicates the type of result set returned by the query resulttype= "Com.edu.hpu.domain.User" Represents an object that encapsulates the result of a query into a user class. The user class is the entity class that the Users table corresponds to <!--get a user object by ID query--<select id=    "GetUser" parametertype= "int" resulttype= "Com.edu.hpu.domain.User" > select * from Users where id=#{id}        </select><!--Create user--<insert id= "AddUser" parametertype= "Com.edu.hpu.domain.User" > Insert into users (name,age) values (#{name},#{age}) </insert> <!--delete User (remove)-<delete ID = "DeleteUser" parametertype= "int" > delete from Users where Id=#{id} </delete> <!--Modify User (Updat E --<update id= "UpdateUser" parametertype= "Com.edu.hpu.domain.User" > Update users set Name=#{name},age =#{age} where Id=#{id} </update> <!--query All users--<select id= "getAllUsers" resulttype= "com.edu.h Pu.domain.User "> select * from Users </select> </mapper>
Through the configuration file implementation of the database additions and deletions are basically completed, and then give the test class,can be tested, as shown below,
Package Com.edu.hpu.test;import Java.util.list;import Com.edu.hpu.domain.user;import com.edu.hpu.util.MyBatisUtil;        Import Org.junit.test;import Org.apache.ibatis.session.sqlsession;public class Test2 {@Test public void Testadd () {        Sqlsession sqlsession = Mybatisutil.getsqlsession (false);        Sqlsession sqlsession = Mybatisutil.getsqlsession (true); /** * Mapping SQL identification String, * Com.edu.hpu.mapping.userMapper is the value of namespace attribute of mapper tag in Usermapper.xml file, * add User is the id attribute value of the insert tag, and the SQL */String statement = "Com.edu.hpu.mapping.userMapper.addU" is found by the ID property value of the insert tag.        Ser ";//Mapping SQL identification string User user = new user ();        User.setname ("New User small yellow");        User.setage (20);        Performs an insert operation int retresult = Sqlsession.insert (Statement,user);        Manually Commit transaction//sqlsession.commit ();        You need to close sqlsession sqlsession.close () after executing SQL with sqlsession;    System.out.println (Retresult);  } @Test public void Testupdate () {      Sqlsession sqlsession = Mybatisutil.getsqlsession (true); /** * Mapping SQL identification String, * Com.edu.hpu.mapping.userMapper is the value of namespace attribute of mapper tag in Usermapper.xml file, * upd Ateuser is the id attribute value of the update tag, and the id attribute value of the update tag can be found to execute SQL */String statement = "Com.edu.hpu.mapping.usermapper.u        Pdateuser ";//Mapping SQL identification string User user = new user ();        User.setid (3);        User.setname ("Hello World");        User.setage (25);        Perform modification operation int retresult = Sqlsession.update (Statement,user);        You need to close sqlsession sqlsession.close () after executing SQL with sqlsession;    System.out.println (Retresult);        } @Test public void Testdelete () {sqlsession sqlsession = Mybatisutil.getsqlsession (true); /** * Mapping SQL identification String, * Com.edu.hpu.mapping.userMapper is the value of namespace attribute of mapper tag in Usermapper.xml file, * del Eteuser is the id attribute value of the delete tag, and the value of the delete tag's ID property can be found to execute SQL */String statement = "COM.EDU.HPU.MAPPING.USERMAPPER.D EleTeuser ";//Map SQL identification string//Perform delete operation int retresult = Sqlsession.delete (statement,4);        You need to close sqlsession sqlsession.close () after executing SQL with sqlsession;    System.out.println (Retresult);        } @Test public void Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession (); /** * Mapping SQL identification String, * Com.edu.hpu.mapping.userMapper is the value of namespace attribute of mapper tag in Usermapper.xml file, * get AllUsers is the id attribute value of the select tag, and the SQL */String statement = "Com.edu.hpu.mapping.userMapper is found by the ID attribute value of the select tag. GetAllUsers ";//Map SQL identification string//Execute query operation, automatically encapsulate query result as list<user> return list<user> lstusers = Sqlsession.sele        Ctlist (statement);        You need to close sqlsession sqlsession.close () after executing SQL with sqlsession;    System.out.println (lstusers); }}

working with AnnotationsIt is necessary to write an interface through annotations, but it does not have to be implemented, as shown below.
package Com.edu.hpu.mapping;import Java.util.list;import Com.edu.hpu.domain.user;import Org.apache.ibatis.annotations.delete;import Org.apache.ibatis.annotations.insert;import Org.apache.ibatis.annotations.select;import org.apache.ibatis.annotations.update;/** * @author GaCl * Defines the interface for SQL mapping, Use annotations to indicate the SQL */public interface Usermapper_11 {//using @insert annotations to specify the Sql@insert ("Insert into Users" (name, age) to perform the Add method. VALUES (#{name}, #{age}) ") public int Add (user user),//Use the @delete annotation to indicate the sql@delete to be performed by the Deletebyid method (" Delete from users where Id=#{id} ") public int deletebyid (int id);//Use the @update annotation to indicate the sql@update to be performed by the Update method (" Update users set name=#{name},age=#{ AGE} where Id=#{id} ') public int update (user user);//Use the @select annotation to indicate the sql@select to be performed by the GetByID method ("select * from Users where id=# {ID} ") public User getById (int id);//Use @select annotations to indicate Sql@select (" SELECT * from users ") to be performed by the GetAll method public list<user> GetAll ();} 

At the same time, you need to add the written interface in the database configuration file, add the following statement in Conf.xml.<mapper class= "Com.edu.hpu.mapping.UserMapper_11"/>

OK, basically done, here is the test class that can be tested,
Package Com.edu.hpu.test;import Java.util.list;import Com.edu.hpu.domain.user;import Com.edu.hpu.mapping.usermapper_11;import Com.edu.hpu.util.mybatisutil;import     Org.apache.ibatis.session.sqlsession;import org.junit.test;/** * @author Administrator * Test the annotations */public class Test3 { @Testpublic void Testadd () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);//Gets the implementation class object of the Usermapper interface, The implementation class object for the Usermapper interface is dynamically constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper = Sqlsession.getmapper ( Usermapper_11.class); User user = new user (); User.setname ("Being Loving"); user.setage; int add = Mapper.add (user);// You need to close sqlsessionsqlsession.close () after executing SQL with sqlsession; System.out.println (add);} @Testpublic void Testupdate () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);//Gets the implementation class object of the Usermapper interface, The implementation class object for the Usermapper interface is dynamically constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper = Sqlsession.getmapper ( Usermapper_11.class); User user = new user (); User.setid (3); User.setname ("Big Sound"); User.setage (26);//The row modification operation int retresult = mapper.update (user),//The Sqlsessionsqlsession.close () needs to be closed after executing SQL with sqlsession; System.out.println (Retresult);} @Testpublic void Testdelete () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);//Gets the implementation class object of the Usermapper interface, The implementation class object for the Usermapper interface is dynamically constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper = Sqlsession.getmapper ( Usermapper_11.class);//perform delete operation int retresult = Mapper.deletebyid (7);// You need to close sqlsessionsqlsession.close () after executing SQL with sqlsession; System.out.println (Retresult);} @Testpublic void Testgetuser () {sqlsession sqlsession = mybatisutil.getsqlsession ();//Gets the implementation class object of the Usermapper interface, The implementation class object for the Usermapperi interface is dynamically constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper = Sqlsession.getmapper ( Usermapper_11.class);//Perform query operations, automatically encapsulate query results into user user = Mapper.getbyid (1);// You need to close sqlsessionsqlsession.close () after executing SQL with sqlsession; SYSTEM.OUT.PRINTLN (user);} @Testpublic void Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession ();//Gets the implementation class object of the Usermapper interface, The implementation class object for the Usermapper interface is made up of sqlsession. Getmapper (Usermapper.class) dynamically constructed Usermapper_11 mapper = Sqlsession.getmapper (usermapper_11.class);//Perform query operations, The query results are automatically encapsulated into list<user> return list<user> lstusers = Mapper.getall ();// You need to close sqlsessionsqlsession.close () after executing SQL with sqlsession; System.out.println (lstusers);}}

This blog is referenced from: http://www.cnblogs.com/xdp-gacl/p/4262895.html

MyBatis realization of data deletion and modification

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.