Mybatis implements additions, deletions, modifications and checks

Posted by robot_nader on Sat, 07 Sep 2019 13:34:11 +0200

The previous article introduced the introduction of Mybatis, followed by the previous continuation, can achieve the addition and deletion of Mybatis check.

First, the test class needs to be modified.

package com.w.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

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 com.w.pojo.User;

public class UserTest1 {

	public static void main(String[] args) throws IOException {
		// Query users according to id
		// getUserById();
		// Fuzzy Query of User List Based on User Name
		// getUserByUsername();
		// Adding users
		// inserUser();
		// Update User
		// updateUser();
		// delete user
		deleteUserById();
	}

	private static void deleteUserById() throws IOException {
		// Load the core configuration file
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// Create sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// Create SqlSession
		SqlSession openSession = sqlSessionFactory.openSession();
		User user = new User();
		user.setId(30);
		int insert = openSession.insert("deleteUserById", user);
		openSession.commit();
		// System.out.println(user.getId());
	}

	// Update User
	private static void updateUser() throws IOException {
		// Load the core configuration file
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// Create sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// Create SqlSession
		SqlSession openSession = sqlSessionFactory.openSession();
		User user = new User();
		user.setId(30);
		user.setAddress("New York");
		user.setBirthday(new Date());
		user.setUsername("lucy");
		user.setSex("1");
		int insert = openSession.insert("updateUser", user);
		openSession.commit();
		// System.out.println(user.getId());
	}

	// Adding users
	private static void inserUser() throws IOException {
		// Load the core configuration file
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// Create sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// Create SqlSession
		SqlSession openSession = sqlSessionFactory.openSession();
		User user = new User();
		user.setAddress("cross");
		user.setBirthday(new Date());
		user.setUsername("lisa");
		user.setSex("2");
		int insert = openSession.insert("inserUser", user);
		openSession.commit();
		System.out.println(user.getId());
	}

	// Query user list based on user name
	private static void getUserByUsername() throws IOException {
		// Load the core configuration file
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// Create sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// Create SqlSession
		SqlSession openSession = sqlSessionFactory.openSession();
		String username = "plum";
		List<User> users = openSession.selectList("getUserByUserName", username);
		for (User user : users) {
			System.out.println(user);
		}
	}

	// Query users according to id
	public static void getUserById() throws IOException {
		// Load the core configuration file
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// Create sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// Create SqlSession
		SqlSession openSession = sqlSessionFactory.openSession();
		// Execute sql statements
		User user = openSession.selectOne("getUserById", 10);
		System.out.println(user);
	}
}

Then modify the UserMapper.xml file in mapper

<?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">
<!-- according to id Search Users -->
<mapper namespace="com.w.mapper.UserMapper">
	<select id="getUserById" parameterType="Integer"
		resultType="com.w.pojo.User">
		select * from user where id=#{v}
	</select>
	<!-- Query user list based on user name -->
	<select id="getUserByUserName" parameterType="String"
		resultType="com.w.pojo.User">
		select * from user where username like '%${value}%'
	</select>
	<!-- Adding users -->
	<insert id="inserUser" parameterType="com.w.pojo.User">
		<selectKey order="AFTER" resultType="Integer"
			keyProperty="id">
			select LAST_INSERT_ID()
		</selectKey>
		insert into user
		(username,birthday,address,sex) values
		(#{username},#{birthday},#{address},#{sex})
	</insert>
	<!-- Update User -->
	<update id="updateUser" parameterType="com.w.pojo.User">
		update user set
		username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
		where id=#{id}
	</update>
	<!-- delete user -->
	<delete id="deleteUserById" parameterType="com.w.pojo.User">
		delete from user where id=#{id}
	</delete>
</mapper>

It's worth mentioning here that when you create a user, because the user ID is self-increasing, you should use the code of selectKey if you want to get the id:

<selectKey order="AFTER" resultType="Integer"
			keyProperty="id">
			select LAST_INSERT_ID()
		</selectKey>

The order means that you write AFTER automatically, that is, the primary key is automatically generated and then taken out. If you write BEFORE, it means that your husband has become an ID and then goes to perform the operation. resultType represents the type, and keyPorperty represents the field in the database table corresponding to the primary key.

Another is that the ${value} is needed for fuzzy queries, not #{arbitrary value}. Because {} represents placeholders, if placed in a database, it represents username='Li', and if ${value} is used, it means username = Li, and queries in the database will result in errors. So using username like'%{username}%'is equivalent to'%'Li'%'. If you want to use {} to write like, you should change it to username like'%{username}'%'.

Above is the basic operation of adding, deleting, modifying and checking. I hope it will be helpful to you. My favorite friends can pay attention to the public number of Weixin: from Xiaobai to Architect. I will update my learning content every day.

Topics: xml Mybatis Java Apache