Use of Mybatis (mapper interface method)

赶牛上岸
Release: 2023-03-20 20:24:02
Original
6879 people have browsed it

Using the Mapper interface, there is no need to write an interface implementation class, and the database operation can be completed directly, which is simple and convenient. In order to help everyone learn the Mapper interface better, the editor has summarized some knowledge points about the Mapper interface, hoping to help those in need.

First go to the structure diagram:
Use of Mybatis (mapper interface method)
The following is the specific code:
1. User.java

实体类中的的get/set方法以及构造方法及toString方法就不贴了 public class User { private int id; private String name; private int age; }
Copy after login

2. UserMapper.java
This is the mapper interface, and the idea of interface-oriented programming is still very important. It is also the most important part of this blog post.

The interface definition has the following characteristics:

  1. The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.

  2. The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.

  3. The return type of the Mapper interface is the same as the resultType of sql defined in UserMapper.xml

Pay attention to the method of creating the table, There is annotation @Param

package com.mi.mapper;import org.apache.ibatis.annotations.Param;import com.mi.beans.User;public interface UserMapper { void createTable (@Param("tableName") String tableName); void add(User user); void del(int id); void update(User user); User getUser(int id); User[] list(); }
Copy after login
Copy after login

3. userMappers.xml
Need to pay attention here
1. The namespace of the xml file must be written as mapper interface The path is as follows.

Copy after login
Copy after login

2. When writing the statement to dynamically create a table, write ${tableName} instead of #{}. Click to view the difference between the two

create table ${tableName}...
Copy after login

The following is the complete code: including table creation, CRUD

         
         
         
         
          create table ${tableName} (id int primary key auto_increment,name varchar(20),age int)
         
         
         
          insert into t_user(name,age) value(#{name},#{age})
         
         
         
          delete from t_user where id = #{id}
         
         
         
          update t_user set name=#{name},age=#{age} where id=#{id}
         
         
         
Copy after login

4, conf.xml
Two things need to be configured here

  • Configuration JDBC connection

  • Configuration mapper.xml

                 
Copy after login

5. SqlSessionUtil.java
I write here A tool class is created, the main purpose is to get the sqlSession, because every time the database is operated in the future, it needs to be written once, so it is encapsulated once.

package com.mi.util;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis. session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtil { public static SqlSession getSqlSession() throws Exception{ String resource = "conf.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Resources.getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //创建能执行映射文件中sql的sqlSession SqlSession sqlSession = sessionFactory.openSession(); return sqlSession; } }
Copy after login

6. MyTest.java
This is a test class. Through the above tool class sqlSession, the most important thing is the following sentence

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Copy after login
Copy after login

MyBatis implements the mapper interfacethrough dynamic proxy. After that, it will be easy to handle. Execute the interface Just use the prepared method.
Be careful not to forget sqlSession.commit() and sqlSession.close(). Otherwise, although no error will be reported during execution, there will be no changes in the database.

这里我只执行了创建表的方法. package com.mi.test;import org.apache.ibatis.session.SqlSession;import com.mi.beans.User;import com.mi.mapper.UserMapper; import com.mi.util.SqlSessionUtil;public class MyTest { public static void main(String[] args) throws Exception { SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.createTable("t_user"); sqlSession.commit(); sqlSession.close(); } }
Copy after login
Copy after login

Using the Mapper interface, there is no need to write an interface implementation class, and the database operation can be completed directly, which is simple and convenient.
First go to the structure diagram:
Use of Mybatis (mapper interface method)
The following is the specific code:
1. User.java

实体类中的的get/set方法以及构造方法及toString方法就不贴了public class User { private int id; private String name; private int age;
Copy after login

2. UserMapper .java
This is the mapper interface, and the idea of interface-oriented programming is still very important. It is also the most important part of this blog post.

The interface definition has the following characteristics:

  1. The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.

  2. The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.

  3. The return type of the Mapper interface is the same as the resultType of sql defined in UserMapper.xml

Pay attention to the method of creating the table, There is annotation @Param

package com.mi.mapper;import org.apache.ibatis.annotations.Param;import com.mi.beans.User;public interface UserMapper { void createTable (@Param("tableName") String tableName); void add(User user); void del(int id); void update(User user); User getUser(int id); User[] list(); }
Copy after login
Copy after login

3. userMappers.xml
Need to pay attention here
1. The namespace of the xml file must be written as mapper interface The path is as follows.

Copy after login
Copy after login

2. When writing the statement to dynamically create a table, write ${tableName} instead of #{}. Click to view the difference between the two

create table ${tableName}...
Copy after login

The following is the complete code: including table creation, CRUD

         
         
         
         
          create table ${tableName} (id int primary key auto_increment,name varchar(20),age int)
         
         
         
          insert into t_user(name,age) value(#{name},#{age})
         
         
         
          delete from t_user where id = #{id}
         
         
         
          update t_user set name=#{name},age=#{age} where id=#{id}
         
         
         
Copy after login

4, conf.xml
Two things need to be configured here

  • Configuration JDBC connection

  • Configuration mapper.xml

                 
Copy after login

5. SqlSessionUtil.java
I write here A tool class is created, the main purpose is to get the sqlSession, because every time the database is operated in the future, it needs to be written once, so it is encapsulated once.

package com.mi.util;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtil { public static SqlSession getSqlSession() throws Exception{ String resource = "conf.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Resources.getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //创建能执行映射文件中sql的sqlSession SqlSession sqlSession = sessionFactory.openSession(); return sqlSession; } }
Copy after login

6. MyTest.java
This is a test class. Through the above tool class sqlSession, the most important thing is the following sentence

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Copy after login
Copy after login

MyBatis implements the mapper interfacethrough dynamic proxy. After that, it will be easy to handle. Execute the interface Just use the prepared method.
Be careful not to forget sqlSession.commit() and sqlSession.close(). Otherwise, although no error will be reported during execution, there will be no changes in the database.

这里我只执行了创建表的方法. package com.mi.test;import org.apache.ibatis.session.SqlSession;import com.mi.beans.User;import com.mi.mapper.UserMapper; import com.mi.util.SqlSessionUtil;public class MyTest { public static void main(String[] args) throws Exception { SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.createTable("t_user"); sqlSession.commit(); sqlSession.close(); } }
Copy after login
Copy after login

Related recommendations:

Mybatis paging plug-in pageHelper example detailed explanation

##Oracle combines Mybatis to implement 10 pieces of data from the table

Spring Boot, Mybatis, Redis quickly build modern Web projects


The above is the detailed content of Use of Mybatis (mapper interface method). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!