MyBatis Learning Tutorial (ii)-How to use MyBatis to perform CRUD operations on the Users table _java

Source: Internet
Author: User
Tags sql using

Previous Article MyBatis Introductory Learning Tutorial (a)-mybatis QuickStart We talked about how to use MyBatis to query the data in the Users table, which is a preliminary introduction to MyBatis. Explain today how to use MyBatis to perform CRUD operations on the Users table. Before you run the theme, you should add some basic knowledge about MyBatis and crud.

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java POJO (Plain old Java Objects, normal Java objects) to records in the database.

MyBatis Download: https://github.com/mybatis/mybatis-3/releases

The meaning of crud

CRUD is the acronym for adding (Create), regain data (Retrieve), update (update), and delete (delete) Several words in the calculation process. It is mainly used to describe the basic operation function of database or persistence layer in software system.

To get to the point, the test environment used in this article is the test environment in the previous article.

Using MyBatis to perform CRUD operations on a table--xml-based implementation

1. Define SQL Mapping XML file

The contents of the Usermapper.xml file are as follows:

<?xml version= "." Encoding= "utf-"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper.//en" "Http://mybatis.org/dtd/mybatis--mapper.dtd" > <!-- Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql mapping file name so that the namespace value is unique, such as namespace= " Me.gacl.mapping.userMapper "is me.gacl.mapping (package name) +usermapper (usermapper.xml file removal suffix)--> <mapper"
Me.gacl.mapping.userMapper "> <!--write the query's SQL statement in the Select tab, set the Select Label ID property to the Getuser,id property value must be unique and cannot be duplicated
Using the ParameterType property to indicate the type of parameter used in the query, the Resulttype property indicates that the result set type returned by the query resulttype= "Me.gacl.domain.User" means that the object that encapsulates the query result into a User class returns The user class is the entity class corresponding to the users table--> <!--get a User object--> <select id= "getuser" "int" parametertype= "me based on ID query . gacl.domain.User "> select * from Users where Id=#{id} </select> <!--Create a user (create)--> <insert id=" Addus Er "parametertype=" me.gacl.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 (Update)--> <update id= "UpdateUser" Parame Tertype= "Me.gacl.domain.User" > Update users set Name=#{name},age=#{age} where Id=#{id} </update> <!-- Query all users--> <select id= "getallusers" resulttype= "Me.gacl.domain.User" > select * from Users </select> </  Mapper>

The

unit test Class code is as follows:

Package me.gacl.test;
Import java.util.List;
Import Me.gacl.domain.User;
Import Me.gacl.util.MyBatisUtil;
Import org.apache.ibatis.session.SqlSession;
Import Org.junit.Test; public class Testcrudbyxmlmapper {@Test public void Testadd () {//sqlsession sqlsession = Mybatisutil.getsqlsession (False
);
Sqlsession sqlsession = Mybatisutil.getsqlsession (true); /** * Maps the identity string of SQL, * Me.gacl.mapping.userMapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * AddUser is the id attribute value of the insert label. You can find the SQL/string statement = "Me.gacl.mapping.userMapper.addUser" to execute by the ID attribute value of the insert label;//Map SQL identity string User user = new
User ();
User.setname ("User aloof wolf");
User.setage ();
Performs an insert operation int retresult = Sqlsession.insert (Statement,user);
Manually submit transaction//sqlsession.commit ();
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult); @Test public void Testupdate () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);/** * Map SQL's identity string, * me.gacl.ma Pping.usermapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * updAteuser is the id attribute value of the update label, which can be found by the ID attribute value of the update label to execute the SQL/String statement = "Me.gacl.mapping.userMapper.updateUser";
/Map SQL identity string User user = new user ();
User.setid ();
User.setname ("aloof Wolf");
User.setage ();
Perform modify operation int retresult = Sqlsession.update (Statement,user);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult); @Test public void Testdelete () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);/** * Map SQL's identity string, * me.gacl.ma Pping.usermapper is the value of the namespace attribute of the Mapper label in the Usermapper.xml file, * DeleteUser is the id attribute value of the delete label. The id attribute value of the delete label allows you to find the SQL/string statement = "Me.gacl.mapping.userMapper.deleteUser" to execute;//Map SQL Identity string//perform delete operation int
Retresult = Sqlsession.delete (statement,);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult); @Test public void Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession ();/** * Map SQL's identity string, * me.gacl.mappin G.usermapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * getallusers is SEThe id attribute value of the lect tag, which can be found by the ID attribute value of the select tag to execute the SQL/String statement = "Me.gacl.mapping.userMapper.getAllUsers";
Map SQL identification string//Execute query operation, automatically encapsulate query results into list<user> return list<user> lstusers = sqlsession.selectlist (statement);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (lstusers);  }
}

Ii. using MyBatis to perform CRUD operations on a table--based on the implementation of annotations

1, define the interface of SQL mapping

The code for the Usermapperi interface is as follows:

 package me.gacl.mapping; import java.util.List; import me.gacl.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 an interface for SQL mappings, using annotations to specify the SQL/public interface to be executed by the method Usermapperi {//using @insert annotations to indicate the SQL @Insert to be executed by the Add method ("Ins
ert into the users (name, age) VALUES (#{name}, #{age}) "is public int add (user user);
Use the @delete note to indicate the SQL @Delete ("Delete from Users where Id=#{id}") to be executed by the Deletebyid method, public int deletebyid (int id); Use the @update note to indicate the SQL @Update that the Update method will execute ("Update users set Name=#{name},age=#{age} where Id=#{id}") public int Update (
User user);
Use the @select note to indicate the SQL @Select that the GetByID method will execute ("Select * from users where Id=#{id}") the public User GetByID (int id);
Use the @select note to indicate the SQL @Select ("Select * from users") to be executed by the GetAll method public list<user> getAll (); }

Need to explain, we do not need to usermapperi interface to write specific implementation class Code, this specific implementation class by the MyBatis to help us dynamically build out, we simply need to use directly.

  2. Register this mapping interface in the Conf.xml file

 <?xml version=" encoding= "utf-"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config.//en" "Http://mybatis.org/dtd/mybatis--config.dtd" > < configuration> <environments default= "Development" > <environment id= "Development" > < TransactionManager type= "JDBC"/> <!--Configure database connection information--> <datasource type= "Pooled" > <property name= "
Driver "value=" Com.mysql.jdbc.Driver "/> <property name=" url "value=" Jdbc:mysql://localhost:/mybatis "/> <property name= "username" value= "root"/> <property name= "password" value= "XDP"/> </dataSource> < 
/environment> </environments> <mappers> <!--registration Usermapper.xml files, Usermapper.xml is located under Me.gacl.mapping This package, so resource written me/gacl/mapping/usermapper.xml--> <mapper resource= "me/ Gacl/mapping/usermapper.xml "/> <!--registration Usermapper mapping Interface--> <mapper class=" Me.gacl.mapping.UserMapperI "/ > </mappers> </configuration> 

The code for the Unit test class is as follows:

Package me.gacl.test;
Import java.util.List;
Import Me.gacl.domain.User;
Import Me.gacl.mapping.UserMapperI;
Import Me.gacl.util.MyBatisUtil;
Import org.apache.ibatis.session.SqlSession;
Import Org.junit.Test; public class Testcrudbyannotationmapper {@Test public void Testadd () {sqlsession sqlsession = mybatisutil.getsqlsession (
true); The implementation class object of Usermapperi interface is obtained, and the implementation class object of Usermapperi interface is constructed by Sqlsession.getmapper (usermapperi.class) Usermapperi mapper =
Sqlsession.getmapper (Usermapperi.class);
User user = new user ();
User.setname ("User XDP");
User.setage ();
int add = mapper.add (user);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (add); @Test public void Testupdate () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);//Get the implementation class object of the Usermapperi interface. The implementation class object of the Usermapperi interface is built dynamically by Sqlsession.getmapper (usermapperi.class) Usermapperi mapper = Sqlsession.getmapper (
Usermapperi.class);
User user = new user ();
User.setid ();
User.setname ("Aloof Wolf _xdp");
User.setage (); Performing Modify operations int reTResult = mapper.update (user);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult); @Test public void Testdelete () {sqlsession sqlsession = Mybatisutil.getsqlsession (TRUE);//Get the implementation class object of the Usermapperi interface. The implementation class object of the Usermapperi interface is built dynamically by Sqlsession.getmapper (usermapperi.class) Usermapperi mapper = Sqlsession.getmapper (
Usermapperi.class);
Perform delete operation int retresult = Mapper.deletebyid ();
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult); @Test public void Testgetuser () {sqlsession sqlsession = mybatisutil.getsqlsession ();//Get the implementation class object of the Usermapperi interface. The implementation class object of the Usermapperi interface is built dynamically by Sqlsession.getmapper (usermapperi.class) Usermapperi mapper = Sqlsession.getmapper (
Usermapperi.class);
Perform a query operation to automatically encapsulate the results of the query into user return user = Mapper.getbyid ();
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
SYSTEM.OUT.PRINTLN (user); @Test public void Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession ();//Get the implementation class object of the Usermapperi interface. of the Usermapperi interface.The implementation class object is constructed by Sqlsession.getmapper (Usermapperi.class) dynamically usermapperi mapper = Sqlsession.getmapper (Usermapperi.class);
Perform query operations, automatically encapsulate the results of the query into list<user> return list<user> lstusers = Mapper.getall ();
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (lstusers);  }
}

The Mybatisutil tool class code used by

is as follows:

Package me.gacl.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 sqlsessionfactory GetSQL
Sessionfactory () {String resource = "Conf.xml";
InputStream is = MyBatisUtil.class.getClassLoader (). getResourceAsStream (Resource);
Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (IS);
return factory; /** * Get sqlsession * @return sqlsession/public static sqlsession Getsqlsession () {return getsqlsessionfactory (). Open
Session (); /** * Get sqlsession * @param isautocommit * True indicates that the Sqlsession object that is created automatically commits the transaction * false after executing SQL, which means that the Sqlsession object that is created does not come out of its own after executing SQL To commit the transaction, we need to manually invoke the Sqlsession.commit () COMMIT TRANSACTION * @return sqlsession/public static sqlsession Getsqlsession (Boolean  Isautocommit) {return getsqlsessionfactory (). Opensession (Isautocommit);}}

The above related code is all the test passed, we can rest assured use!

The above is small set to introduce the MyBatis Learning Tutorial (ii)-How to use the MyBatis on the Users table to perform CRUD operations, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.