Pre-preparation
To create a new Java project or Java Wweb Project, you need to import the following packages
The basic work is done, and the next step is to get started.
New entity class
To create 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 corresponds
private int id;
private String name;
private int age;
Encapsulate a property 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 age) {
this.age = age;
}
Add ToString Method
@Override public
String toString () {return
"User [id=" + ID + ", name=" + name + ", age=" + A GE + "]";
Add MyBatis Tool Class
Add the tool class 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 sqlsessionfactory G Etsqlsessionfactory () {String resource = "conf.xml";//Fetch configuration file InputStream is = MyBatisUtil.class.getClassLoader (). getre
Sourceasstream (Resource);
Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (IS);
return factory; /** * Get sqlsession * @return sqlsession/public static sqlsession Getsqlsession () {return getsqlsessionfactory (
). Opensession (); /** * 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 created after executing the SQL Does not automatically commit the transaction, then we need to manually invoke Sqlsession.commit () COMMIT TRANSACTION * @return sqlsession/public static sqlsession Getsqlsession (Boolean IsA Utocommit) {return getsqlsessionfactory (). Opensession (Isautocommit); }
}
Using MyBatis to check and delete data, there are two methods, namely, profile operation and annotation operation.
Operating through a configuration file
The 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"/> <!--Configure database connection information--> <datasource type= "Pooled" > <property name= "Drive R "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= "password" value= "admin"/> </dataSource> </environment> </environmen Ts> <mappers> <!--registered 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 shown below,
<?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" > <!--to write the query's SQL statement in the Select tab, set the Select label's ID attribute to GetUser, The id attribute value must be unique, and the ParameterType property cannot be reused to indicate the type of parameter used in the query, and the Resulttype property indicates the result set type returned by the query resulttype= "Com.edu.hpu.domain.User" The object that encapsulates the query result into a user class returns the user class is the entity class corresponding to the users table--> <!--gets a user object--> <select id= "GetUser" based on the ID query paramete rtype= "int" resulttype= "Com.edu.hpu.domain.User" > select * from Users where Id=#{id} </select> <!--create User (C reate)--> <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 f Rom users where id=#{id} </delete> <!--Modify User (Update)--> <update id= "UpdateUser" parametertype=. Hpu.dOmain. User "> Update users set Name=#{name},age=#{age} where Id=#{id} </update> <!--query All users--> <select id=" GetAllUsers "resulttype=" Com.edu.hpu.domain.User "> select * from Users </select> </mapper>
Through the configuration file implementation of the database additions and deletions have been basically completed, next to 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); /** * Maps the identity string of SQL, * Com.edu.hpu.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, and you can find the SQL/String statement = "Com.edu.hpu.mapping.userMapper.addUser" to execute by the ID attribute value of the insert label
;//Mapping SQL identity 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 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); /** * Mapping SQL's identity string, * com.edu.hpu.mapping.userMapper is UThe value of the namespace property of the mapper tag in the Sermapper.xml file, * UpdateUser is the id attribute value of the update label, and the id attribute value of the update label allows you to find the SQL/String to execute
statement = "Com.edu.hpu.mapping.userMapper.updateUser";//Map SQL ID string User user = new user ();
User.setid (3);
User.setname ("Hello World");
User.setage (25);
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); /** * Maps the identity string of SQL, * Com.edu.hpu.mapping.userMapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * DeleteUser is the value of the id attribute of the delete label, which can be found by the value of the id attribute of the delete label to execute the SQL/String statement = "
Com.edu.hpu.mapping.userMapper.deleteUser//Mapping SQL Identity string//perform delete operation int retresult = Sqlsession.delete (statement,4);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult);
@Test public void Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession ();
/*** Mapping SQL's identity string, * Com.edu.hpu.mapping.userMapper is the value of the namespace attribute of the mapper tag in the Usermapper.xml file, * The getallusers is the id attribute value of the Select label, which can be found by the ID attribute value of the select tag to execute the SQL/String statement = " com.edu.hpu.mapping.userMapper.getAllUsers//Mapping 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); }
}
Working with annotations
Working with annotations requires writing an interface, but 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 an interface for SQL mappings, using annotations to specify the SQL/public interface to be executed by the method Usermapper_11 {//using @insert annotations to indicate the SQL @Ins to execute by the Add method
ERT ("INSERT 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 (using
R 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 (); }
Also, you need to add the written interface to the database configuration file and add the following statement to the Conf.xml.
<mapper class= "Com.edu.hpu.mapping.UserMapper_11"/>
OK, basically done, here's a 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 annotation * * public class Test3 {@Test public void Testadd () {sqlsession sqlsession = M
Ybatisutil.getsqlsession (TRUE); The implementation class object of Usermapper interface is obtained, and the implementation class object of Usermapper interface is constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper =
Sqlsession.getmapper (Usermapper_11.class);
User user = new user ();
User.setname ("Being loving");
User.setage (20);
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); The implementation class object of Usermapper interface is obtained, and the implementation class object of Usermapper interface is constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper =
Sqlsession.getmapper (Usermapper_11.class); User user = new user ();
User.setid (3);
User.setname ("Da Yin Xi Sound");
User.setage (26);
Perform modify operation 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); The implementation class object of Usermapper interface is obtained, and the implementation class object of Usermapper interface is 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 sqlsession sqlsession.close () after executing SQL using sqlsession.
System.out.println (Retresult);
@Test public void Testgetuser () {sqlsession sqlsession = mybatisutil.getsqlsession (); The implementation class object of Usermapper interface is obtained, and the implementation class object of Usermapperi interface is constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper =
Sqlsession.getmapper (Usermapper_11.class);
Perform a query operation to automatically encapsulate the results of the query into user return user = Mapper.getbyid (1);
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
SYSTEM.OUT.PRINTLN (user); } @Test Public VoiD Testgetall () {sqlsession sqlsession = mybatisutil.getsqlsession (); The implementation class object of Usermapper interface is obtained, and the implementation class object of Usermapper interface is constructed by Sqlsession.getmapper (usermapper.class) Usermapper_11 mapper =
Sqlsession.getmapper (Usermapper_11.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 above is a small series to introduce the MyBatis to realize the data and additions and deletions to check the example, 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!