Basic operations of Mybatis on Database

Connect to the database through the XML configuration file and configure the path of the XML file that executes the SQL statement

<?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" />
			<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="20001101pyj" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="EmployeeMapper.xml" />
		<mapper resource="EmployeeMapperPlus.xml" />
	</mappers>
</configuration>

The XML file in the < mapper > tag is used to write SQL statements

Specification for creating operation database through interface

public interface EmployeeMapper {
	public Employee getEmpById(int id);
	
	public List<Employee> getEmpByNameLike(@Param("name")String name);
	
	public void addEmp(Employee emp);
	
	public void insert(@Param("lastName")String lastName,@Param("email")String         
    email,@Param("gender")String gender);
	
	public void update(int id,String lastName,String gender,String email);
	
	public void deleteById(int id);
}

XML file corresponding to the interface

namespace="com.pyj.mybatis.dao.EmployeeMapper" is to establish contact with the corresponding interface

<?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.pyj.mybatis.dao.EmployeeMapper">
	<select id="getEmpById"
		resultType="com.pyj.mybatis.bean.Employee">
		select id,last_name lastName,gender,email from tbl_employee where id = #{id}
	</select>
	
	<select id="getEmpByNameLike" resultType="com.pyj.mybatis.bean.Employee">
		select id,last_name lastName,gender,email from tbl_employee where last_name like #{name}
	</select>
	
	<insert id="insert"
		parameterType="com.pyj.mybatis.bean.Employee">
		insert into tbl_employee(last_name,email,gender)
		values(#{lastName},#{email},#{gender})
	</insert>
	
	<insert id="addEmp"
		parameterType="com.pyj.mybatis.bean.Employee">
		insert into tbl_employee(last_name,email,gender)
		values(#{lastName},#{email},#{gender})
	</insert>
	
	<update id="update">
		update tbl_employee
		set last_name=#{param2},gender=#{param4},email=#{param3}
		where id=#{param1}
	</update>
	
	<delete id="deleteById">
		delete from tbl_employee where id=#{id}
	</delete>
	
</mapper>

Add, delete, modify and query

increase

Add in the XML file through < Insert >, where id corresponds to the corresponding method in the interface, and parameterType is the incoming type (writable or not)

<insert id="insert"
		parameterType="com.pyj.mybatis.bean.Employee">
		insert into tbl_employee(last_name,email,gender)
		values(#{lastName},#{email},#{gender})
	</insert>
	
	<insert id="addEmp"
		parameterType="com.pyj.mybatis.bean.Employee">
		insert into tbl_employee(last_name,email,gender)
		values(#{lastName},#{email},#{gender})
	</insert>

#{} corresponds to the input data

1. The method in the interface creates a name for each attribute through the annotation @ Param("lastName") for easy application in #{}.

	public void insert(@Param("lastName")String lastName,@Param("email")String         
    email,@Param("gender")String gender);

2. The method in the interface passes in a specific object and #{} fills in the specific attributes of the object

public void addEmp(Employee emp);

In addition to the above two methods, if you want to #{} assign values to SQL statements, you can also write param1 and param2 successively according to the order of incoming values. See update method for details

Delete

Delete the XML file through < delete >

    <delete id="deleteById">
		delete from tbl_employee where id=#{id}
	</delete>

Methods in corresponding interfaces

public void deleteById(int id);

If there is only one value passed in, the corresponding variable can be written directly in #{}

change

Update the XML file through < update >

    <update id="update">
		update tbl_employee
		set last_name=#{param2},gender=#{param4},email=#{param3}
		where id=#{param1}
	</update>

Methods in corresponding interfaces

public void update(int id,String lastName,String gender,String email);
	

At this time, neither an object is passed in nor annotated, so param is written in #{}

check

Query through < Select > in XML file

1. Check a piece of data. resultType is the data type obtained

    <select id="getEmpByid" resultType="com.pyj.mybatis.bean.Employee">
		select id,last_name lastName,gender,email from tbl_employee where id=#{name}
	</select>

Methods in corresponding interfaces

public Employee getEmpById(int id);

2. Check a pile of data

    <select id="getEmpByNameLike" resultType="com.pyj.mybatis.bean.Employee">
		select id,last_name lastName,gender,email from tbl_employee where last_name like #{name}
	</select>

Methods in corresponding interfaces

public List<Employee> getEmpByNameLike(@Param("name")String name);

If the attribute of A class object A is still A class object B, the data queried by the SQL statement can only be the attribute value of object B, and the data of object B queried cannot be encapsulated into object B (temporary understanding: the column names in the database do not correspond to object B). At this time, the resultMap tag is needed to implement

Replace the resultType tag above with the resultMap tag, and correspond the relationship in the resultMap

Column represents the column name in the database, and property represents the name of the class object in java

dept is class B, and dname is one of its attributes

<mapper namespace="com.pyj.mybatis.dao.EmployeeMapperPlus">
	<resultMap type="com.pyj.mybatis.bean.EmployeeAndDep" id="Emp">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
		<result column="name" property="dept.dname"/>
	</resultMap>
	
	<select id="getEmpAndDept" resultMap="Emp">
		SELECT e.`id`,e.`last_name`,e.`email`,e.`gender`,d.`name` FROM tbl_employee e,development d
		WHERE e.`d_id`=d.`id` AND e.`id`= #{id}
	</select>
</mapper>

The method in the corresponding interface (EmployeeAndDep is class A)

public EmployeeAndDep getEmpAndDept(Integer id);

Concrete implementation

First, contact the main XML file to find all XML configuration files that can execute SQL statements. On this basis, create a factory sqlSessionFactory to create the executor openSession

openSession.getMapper(EmployeeMapperPlus.class) method is to find the corresponding interface through the class of the interface

At the beginning of this article, the XML file that executes SQL statements is connected with the corresponding interface through namespace="com.pyj.mybatis.dao.EmployeeMapper"

mapper is the implementation class of the interface The methods in the interface can execute SQL statements

If you add, delete or modify, you may need to submit

public void test() throws Exception {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory =
		 new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
			EmployeeAndDep ead=mapper.getEmpAndDept(1);
		}finally {
			openSession.close();
		}
	}

Keywords: Database MySQL Mybatis

Added by expl0it on Sat, 22 Jan 2022 07:20:28 +0200