Preparation
To create a new java project or java wweb project, you need to import the following packages.
The basic work has been completed, and then we will start to get to the topic.
Create a new entity class
Create a new entity class corresponding to the database table
package com.edu.hpu.domain; /** * @author Administrator *Entity class corresponding to the user table*/ public class User { //The attributes of the entity class and the field names of the table correspond to private int id; private String name; private int age; //Encapsulate the attributes 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=" + age + "]"; } }Add Mybatis tool class
The tool class added 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.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * Get SqlSessionFactory * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { String resource = "conf.xml";//Click the configuration file 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().openSession(); } /** * Get SqlSession * @param isAutoCommit * true means that the created SqlSession object will automatically submit the transaction after SQL is executed * false means that the created SqlSession object will not automatically submit the transaction after SQL is executed. At this time, we need to call sqlSession.commit() manually to submit the transaction* @return SqlSession */ public static SqlSession getSqlSession(boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } }There are two methods for adding, deleting, searching and modifying data using mybatis, namely configuration file operation and annotation operation.
Operation through configuration files
The database configuration file is as follows, configure 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="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="password" value="admin" /> </dataSource> </environment> </environments> <mappers> <!-- Register userMapper.xml file, userMapper.xml is located in the package com.edu.hpu.mapping, so resource is written as com/edu/hpu/mapping/userMapper.xml--> <mapper resource="com/edu/hpu/mapping/userMapper.xml"/> <!-- <mapper/> --> </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"> <!-- Write query SQL statements in the select tag, Set the id attribute of the select tag to getUser. The id attribute value must be unique. The parameterType attribute cannot be reused to indicate the parameter type used in the query. The resultType attribute indicates the result set type returned by the query resultType="com.edu.hpu.domain.User" means that the query result is encapsulated into an object of the User class and returns to the User class, which is the entity class corresponding to the users table--> <!-- Get a user object based on the id query--> <select id="getUser" parameterType="int" resultType="com.edu.hpu.domain.User"> select * from users where id=#{id} </select> <!-- Create user (Create) --> <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 (Update) --> <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.hpu.domain.User"> select * from users </select> </mapper> The database addition, deletion, and revision through configuration files has been basically completed. Next, the test class is given.
Tests can be performed 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); /** * Map SQL identification string, * 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 tag, and the SQL to be executed can be found through the id attribute value of the insert tag */ String statement = "com.edu.hpu.mapping.userMapper.addUser";//Map SQL identification string User user = new User(); user.setName("New User Xiaohuang"); user.setAge(20); //Perform the insert operation int retResult = sqlSession.insert(statement,user); //Manually submit transactions//sqlSession.commit(); //After executing SQL using SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); /** * Map SQL Identification String, * com.edu.hpu.mapping.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 tag. The SQL to be executed can be found through the id attribute value of the update tag */ String statement = "com.edu.hpu.mapping.userMapper.updateUser";//Mapping SQL ID string User user = new User(); user.setId(3); user.setName("hello world"); user.setAge(25); //Execute the modification operation int retResult = sqlSession.update(statement,user); // After executing SQL with SqlSession, you need to close SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); /** * Map SQL identification string, * com.edu.hpu.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file, * deleteUser is the id attribute value of the delete tag, and the SQL to be executed can be found through the id attribute value of the delete tag */ String statement = "com.edu.hpu.mapping.userMapper.deleteUser";//Mapping the sql's identification string//Perform a delete operation int retResult = sqlSession.delete(statement,4); //After executing SQL using SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * Mapping the sql's identification string, * com.edu.hpu.mapping.userMapper is the value of the namespace attribute of the mapper tag in the userMapper.xml file. * getAllUsers is the id attribute value of the select tag. The SQL to be executed can be found through the id attribute value of the select tag */ String statement = "com.edu.hpu.mapping.userMapper.getAllUsers";//Mapping the sql identity string//Execute the query operation and automatically encapsulate the query result into List<User> Return List<User> lstUsers = sqlSession.selectList(statement); // After executing SQL with SqlSession, you need to close SqlSession sqlSession.close(); System.out.println(lstUsers); } }Operation through annotations
Operation through annotations requires writing an interface, but it does not need 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 * Define the interface for SQL mapping, specify the SQL to be executed using annotations */ public interface UserMapper_11 { //Use the @Insert annotation to specify the SQL to be executed by the add method @Insert("insert into users(name, age) values(#{name}, #{age})") public int add(User user); //Use the @Delete annotation to specify the SQL to be executed by the deleteById method @Delete("delete from users where id=#{id}") public int deleteById(int id); //Use the @Update annotation to specify the SQL to be executed by the update method @Update("update users set name=#{name},age=#{age} where id=#{id}") public int update(User user); //Use the @Select annotation to specify the SQL to execute the getById method @Select("select * from users where id=#{id}") public User getById(int id); //Use the @Select annotation to specify the SQL to execute the getAll method @Select("select * from users") public List<User> getAll(); }At the same time, you need to add the written interface to the database configuration file and add the following statement in conf.xml.
<mapper/>
OK, it has basically been completed, 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 annotation*/ public class Test3 { @Test public void testAdd(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); //Get the implementation class object of the UserMapper interface. The implementation class object of 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("Great wisdom is foolish"); user.setAge(20); int add = mapper.add(user); //SqlSession needs to be closed after executing SQL with SqlSession sqlSession.close(); System.out.println(add); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); //Get the implementation class object of the UserMapper interface. The implementation class object of 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 and sound"); user.setAge(26); //Execute the modification operation int retResult = mapper.update(user); //After executing SQL using SqlSession, you need to close SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(true); //Get the implementation class object of the UserMapper interface, and the implementation class object of the UserMapper interface is dynamically built by sqlSession.getMapper(UserMapper.class) UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11.class); //Execute the delete operation int retResult = mapper.deleteById(7); //After using SqlSession to execute SQL, you need to close SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetUser(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //Get the implementation class object of the UserMapper interface. The implementation class object of the UserMapperI interface is dynamically constructed by sqlSession.getMapper(UserMapper.class) UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11.class); //Execute the query operation and automatically encapsulate the query result into User Return User user = mapper.getById(1); //After using SqlSession to execute SQL, you need to close SqlSession sqlSession.close(); System.out.println(user); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //Get the implementation class object of the UserMapper interface. The implementation class object of the UserMapper interface is dynamically constructed by sqlSession.getMapper(UserMapper.class) UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11.class); //Execute query operations and automatically encapsulate the query results into List<User> Return List<User> lstUsers = mapper.getAll(); //After using SqlSession execution SQL, you need to close SqlSession sqlSession.close(); System.out.println(lstUsers); } }The above is a detailed explanation of the mybatis implementation of data addition, deletion, and revision that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply you in time. Thank you very much for your support to Wulin.com website!