Cover: Luo Xiaoxi
Author: Pan Pan
Execute in comprehension, understand in execution, and learn techniques the same way.
preface
In the last article “Mybatis series complete solution (II) : Mybatis Introduction and Environment construction”, we made a preliminary explanation of Mybatis, and built a set of basic environment, and completed a query operation together. Therefore, on this basis, we continue to expand the insert, modify and delete operations to improve our CRUD basic operations.
Mybaits Series full solutions (continuously updated)
- Mybatis series full solution (a) : handwriting a set of persistent layer frame
- Mybatis series full solution (2) : Mybatis introduction and environment construction
- Mybatis series full solution (3) : Mybatis simple CRUD use introduction
- Mybatis series full solution (four) : the most complete network! Mybatis configuration file XML overview
- Mybatis series full solution (5) : the most complete network! Mybatis Mapper mapping file
- Mybatis series full solution (6) : Mybatis most core API you know how many?
- Mybatis series full solution (7) : Dao layer two ways to achieve
- Mybatis series full solution (8) : Mybatis dynamic SQL
- Mybatis series full solution (9) : Complex mapping of Mybatis
- Mybatis series full solution (10) : Mybatis annotation development
- Mybatis series full solution (11) : Mybatis cache full solution
- Mybatis plug-in development
- Mybatis series full solution (13) : Mybatis code generator
- Spring integrates Mybatis
- Mybatis series full solution (15) : SpringBoot integrated Mybatis
- Mybatis series full solution (16) : Mybatis source code analysis
directory
1. Review of Mybatis query operation
2. Insert operation
3. Modify operations
4. Delete operations
5, summary
Mybatis query operation review
The Java development environment, Mysql database, and Maven environment have been installed by default.
Mybatis query is divided into 7 steps:
1. Create maven project
2, Add MyBatis repository coordinates (not maven project)
Create table user
4. Write the User entity class
5. Write the mapping file usermapper.xml
6. Compile the core file SQLMAPconfig.xml
7. Write test classes
1. Create maven project
2. Add MyBatis warehouse coordinates
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<! - mybatis coordinates - >
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<! -- Mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<! -- Unit test coordinates -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<! -- Log coordinates -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
Copy the code
Create table user
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`birthday` varchar(50) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
Copy the code
4. Write the User entity class
package com.panshenlian.pojo;
/ * * *@Author: panshenlian
* @Description: user entity *@Date: Create in 2:08 2020/11/28
*/
public class User {
private int id;
private String username;
private String password;
private String birthday;
public int getId(a) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername(a) {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword(a) {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday(a) {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString(a) {
return "User{" +
"id=" + id +
", username='" + username + '\' ' +
", password='" + password + '\' ' +
", birthday='" + birthday + '\' ' +
'} '; }}Copy the code
5. Write the mapping file usermapper.xml
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.panshenlian.pojo.User">
select * from User
</select>
</mapper>
Copy the code
6. Compile the core file SQLMAPconfig.xml
<! DOCTYPEconfiguration 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" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="/UserMapper.xml" />
</mappers>
</configuration>
Copy the code
7. Write test classes
package com.panshenlian.service;
import com.panshenlian.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/ * * *@Author: panshenlian
* @Description: Experience testing *@Date: Create in 2:21 2020/11/28
*/
public class MybatisTest {
@Test
public void testQueryUser01(a) throws IOException {
// Load the core configuration file
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get the sqlSession factory object
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// Get the sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
// Execute the SQL statement
List<User> userList = sqlSession.selectList("userMapper.findAll");
// Print the result
for (User user : userList) {
System.out.println(user);
}
// Release resourcessqlSession.close(); }}Copy the code
Finally, the Junit unit test was passed, and the results were as expected:
Engineering structure reference:
The insert
Insert data operation of Mybatis, we need two steps altogether:
- Add insert statements to the mapping file usermapper.xml
<! Insert user action -->
<insert id="insertUser"
parameterType="com.panshenlian.pojo.User" >
insert into user(username,password,birthday)
values ( #{username}, #{password},#{birthday})
</insert>
Copy the code
- Write Java code to insert User entity objects
@Test
public void testInsertUser01(a) throws IOException {
// Load the core configuration file
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get the sqlSession factory object
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// Get the sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
// Prepare the object to be inserted into the database
User insertUser = new User();
insertUser.setBirthday("2020-12-01");
insertUser.setUsername("panpan");
insertUser.setPassword("888");
// Execute the SQL statement
int rows = sqlSession.insert("userMapper.insertUser",insertUser);
// Print the result
System.out.println(rows);
// Commit the transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}
Copy the code
* * note: Commit (); commit(); insert, update, delete); commit(); If openSession(true) is used to open the session, then the transaction is committed automatically, without manually calling commit().
During the insertion operation, the resultType parameter is not configured in the mapping file, that is, the returned resultType is not configured. Mybatis returns int type by default, indicating the number of records affected by the insertion operation.
If the result of the previous insert operation is 1, the insert is successful and only one record is affected.
Note problems in insert operations
Insert statements use insert tags
2. Specify the data type to be inserted using the parameterType attribute in the mapping file
3. Use #{entity attribute name} in Sql statement to reference entity attribute value
Sqlsession. insert(namespace. id, entity object);
Sqlsession.mit () = sqlsession.mit ();
Modify the operating
The operation of modifying data in Mybatis, same as the operation of inserting, also needs two steps:
- Add the modification statement to the mapping file usermapper.xml
<! -- Modify user actions -->
<insert id="updateUser" parameterType="com.panshenlian.pojo.User" >
update user set username =#{username} where id = #{id}
</insert>
Copy the code
- Write Java code that modifies the User entity object
@Test
public void testUpdateUser01(a) throws IOException {
// Load the core configuration file
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get the sqlSession factory object
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// Get the sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
User updateUser = new User();
updateUser.setUsername("New username PanPan");
updateUser.setId(1);
// Execute the SQL statement
int rows = sqlSession.update("userMapper.updateUser",updateUser);
// Print the result
System.out.println(rows);
// Commit the transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}
Copy the code
The result is as follows: The data record whose ID is 1 is successfully modified. The new user name is PanPan
Caution During the modification operation
1. Use the UPDATE tag to modify the statement
Sqlsession. update(namespace. id, entity object);
Delete operation
Delete data operation of Mybatis, same as the above insert and modify operation, also need two steps:
- Add delete statements to the mapping file usermapper.xml
<! -- Delete user -->
<insert id="deleteUser" parameterType="com.panshenlian.pojo.User" >
delete from user where id=#{id} and username = #{username}
</insert>
Copy the code
- Write Java code that removes the User entity object
! [delete](C:\Users\Super Man\Desktop\delete.png)@Test
public void testDeleteUser01(a) throws IOException {
// Load the core configuration file
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get the sqlSession factory object
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// Get the sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
User deleteUser = new User();
deleteUser.setUsername("New username PanPan");
deleteUser.setId(1);
// Execute the SQL statement
int rows = sqlSession.delete("userMapper.deleteUser",deleteUser);
// Print the result
System.out.println(rows);
// Commit the transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}
Copy the code
The result is as follows: Data records where id =1 and username= PanPan are deleted successfully.
Caution During the deletion operation
Delete statements use the delete tag
2. Use #{entity attribute name} in Sql statements to reference object attributes passed
Sqlsession. delete(namespace. id,Object);
For example, when parameterType is set to “java.lang.Integer” in the mapping file, the actual API is sqlsession. delete(” namespace.id “,1).
conclusion
Through the introduction of this paper, we have basically mastered the most basic CRUD operation of Mybatis. In the follow-up, we will go deeper step by step.
Mybatis: XML configuration files and APIS
BIU ~ the article continues to update, wechat search “Pan Pan and his friends” the first time to read, there are surprises at any time. This article will be included on GitHub github.com/JavaWorld, hot technology, framework, surface, solution, we will be the most beautiful posture in the first time, welcome Star.