Use MyBatis mapper for database operations

Use MyBatis mapper to achieve database operations, common three ways

  1. Pure XML mapper, the use of SqlSession to achieve a variety of methods to add, delete, change and check
  2. A hybrid type of XML mapper + interface mapper
  3. A hybrid form of annotations + interface mapper

XML + interface mapper, annotations + interface mapper are common methods in development, the specific differences are as follows:

  • XML mapper + interface mapper, SQL are written in XML, the overall code coupling degree is low, it is difficult to write

  • Annotation + interface mapper, SQL written in the annotation, the overall code is simple, easy to develop, but the coupling degree of the code is high

Pure XML mapper

It is roughly divided into four files: the master configuration file, the XML mapper, the entity class, and the caller

Master profile

<? The 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> <! <environment 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/demo? useUnicode=true&amp; characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <! -- master config file imports mapper --> <mappers> <! -- Resource attribute, representing the current mapper configuration is the value of the imported XML mapper attribute, which is the package name of the mapper. Replace it with /, and then concatenate the mapper's file name. Suffix - > < mapper resource = "com/test/day38 StudentMapper. XML" / > < / mappers > < / configuration >Copy the code

XML mapper

<? The 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" > <! Can choose any name, namespace, the only, but the best to define a certain rules, facilitate subsequent use - - > < mapper namespace = "com. Test. Day38. StudentMapper" > <! Insert tag indicates the SQL ID attribute of "insert", the current insert tag uniquely identifies, This value is unique (in the current configuration file) parameterType. This attribute indicates the wrapper class from which the SQL statement fetched the arguments in the SQL statement. #{ID} indicates the id attribute from the corresponding class object in parameterType --> < INSERT id="insert" parameterType="com.test.day38.Student"> insert into student(id,name) values (#{id},#{name}); </insert> </mapper>Copy the code

Caller: Tests using the XML mapper to manipulate the database

Public class XmlMapperTest {public static void main(String[] args) throws Exception{// Loads the master configuration file, which contains database connection information. And the mapping information / / parameter is the main configuration file path, with our main configuration file is in the path, so write the file name can be directly Reader Reader = Resources. GetResourceAsReader (" myBatis - config. XML ");  SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); / / get the SqlSession objects, the object is operating mapper object SqlSession session = sqlSessionFactory. OpenSession (); Student stu = new Student(); stu.setId(37); SetName (" XML mapper "); /** * session.insert to operate on the inset parameter 1 of the mapper, locate the mapper's namespace and its own ID concatenation. For example com. Test. Day38. StudentMapper. Insert 2 * parameters, Is to transfer to the parameters of the mapper * / int res = session. The insert (" com. Test. Day38. StudentMapper. Insert ", stu); // The parameterType parameter in the mapper specifies the source of the stU: system.out.println (res); // submit session session.mit (); // Close the resource and session reader.close(); session.close(); }}Copy the code

The entity class for testing

Public class Student implements Serializable{// When you want to save an in-memory object to a file or database, Private static Final Long serialVersionUID = 1L; // The serialVersionUID variable is called the Serializable version number. It is mainly used in classes that implement Serializable. public String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code

Interface mixed with XML mapper

There are roughly five files: the master configuration file, the XML mapper, the interface, the entity class, and the caller

Master profile

<? The 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> <! <environment 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/demo? useUnicode=true&amp; characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <! -- master config file imports mapper --> <mappers> <! -- Resource attribute, representing the current mapper configuration is the value of the imported XML mapper attribute, which is the package name of the mapper. Replace it with /, and then concatenate the mapper's file name. Suffix - > < mapper resource = "com/test/day38 StudentMapperIn. XML" / > < / mappers > < / configuration >Copy the code

XML mapper

<? The 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" > <! The namespace attribute value of the mapper tag is the full name of the interface (package name). Mapper namespace="com.test.day38.StudentIn"> <! -- The insert tag represents the SQL ID attribute to be inserted. The current insert tag uniquely identifies that this value is unique (in the current configuration file) and is used in the interface with the XML mapper. ParameterType is the full name of the enclosing class for the parameter passed to the current SQL. parameterType="com.test.day38.Student"> insert into student(id,name) values (#{id},#{name}); </insert> </mapper>Copy the code

interface

package com.test.day38; Public interface StudentIn {@param stu * @return */ public int insert(Student) stu); }Copy the code

Callers: interface and mapper mixed

public class XmlAndInMapperTest { public static void main(String[] args) { Reader reader = null; SqlSessionFactory sqlSessionFactory = null; SqlSession session = null; Try {// Load the main configuration file, which contains database connection information and mapper information // The main configuration file path, our main configuration file is under the path, So write the file name can be directly reader = Resources. GetResourceAsReader (" myBatis - config. XML "); SqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); / / get the SqlSession objects, the object is operating the object mapper session = sqlSessionFactory openSession (); Student stu = new Student(); stu.setId(38); SetName (" Interface mixed with XML mapper "); // Operation interface and XML hybrid mapper /** here is the difference * getMapper(interface class). The SQL * interface that uses session.insert to operate on the inset of the mapper is mixed with the mapper, using the interface instead of session.insert. */ int res = session.getmapper (studentin.class).insert(stu); System.out.println(res); // submit session session.mit (); }catch(Exception e){// If an Exception occurs session.rollback(); }finally{// Close the resource try {reader.close(); } catch (IOException e) { e.printStackTrace(); } session.close(); }}}Copy the code

The entity class for testing

package com.test.day38; Public Class Student implements Serializable{// When you want to save an in-memory object to a file or database, you need to serialize a class of objects using Java SE before /** * serialization. In mybatis, why should the entity class be serialized? ParameterType ="Student" parameterType="Student" parameterType="Student" */ private static Final Long serialVersionUID = 1L; // The serialVersionUID variable is called the Serializable version number. It is mainly used in classes that implement Serializable. public String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code

Annotations are mixed with the interface mapper

It is roughly divided into four files: the master configuration file, the annotated interface, the entity class, and the caller

Master profile

<? The 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> <! <environment 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/demo? useUnicode=true&amp; characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <! -- master config file imports mapper --> <mappers> <! The class attribute is used to introduce the interface mapper, using the annotation + interface mapper value is the interface package name. The interface name - > < mapper class = "com. Test. Day38. StudentIn2" / > <! If each interface is introduced using class=" XXX ", there will be a lot of such configurations. To avoid this situation, you can configure the package name directly. This imports all the annotated interfaces under the package --> <package name="com.test.day38" /> </mappers> </configuration>Copy the code

Annotated interfaces

package com.test.day38; Public interface StudentIn2 {/** * @insert Insert("") string parameter is the SQL statement of Insert tag @param stu * @return */ @Insert("insert into student(id,name) values (#{id},#{name});" ) public int insert(Student stu); }Copy the code

Callers: interface and annotation mix

public class XmlAndInMapperTest { public static void main(String[] args) { Reader reader = null; SqlSessionFactory sqlSessionFactory = null; SqlSession session = null; Try {// Load the main configuration file, which contains database connection information and mapper information // The main configuration file path, our main configuration file is under the path, So write the file name can be directly reader = Resources. GetResourceAsReader (" myBatis - config. XML "); SqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); / / get the SqlSession objects, the object is operating the object mapper session = sqlSessionFactory openSession (); Student stu = new Student(); // stu.setId(39); // stu.setName(" interface and annotation mix "); stu.setId(40); SetName (" Test the way the interface mapper is referenced by package name "); /** * getMapper(interface class) Int res = session.getmapper (studentin.class).insert(stu); / / int res = session.getmapper (studentin.class). System.out.println(res); // submit session session.mit (); }catch(Exception e){// If an Exception occurs session.rollback(); }finally{// Close the resource try {reader.close(); } catch (IOException e) { e.printStackTrace(); } session.close(); }}}Copy the code

The entity class for testing

package com.test.day38; Public class Student implements Serializable{// When you want to save an in-memory object to a file or database, Private static Final Long serialVersionUID = 1L; // The serialVersionUID variable is called the Serializable version number. It is mainly used in classes that implement Serializable. public String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code