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:
The following is the specific code:
1. User.java
实体类中的的get/set方法以及构造方法及toString方法就不贴了 public class User { private int id; private String name; private int age; }
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:
The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.
The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.
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(); }
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.
<mapper namespace="com.mi.mapper.UserMapper">
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}...
The following is the complete code: including table creation, CRUD
<mapper namespace="com.mi.mapper.UserMapper">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}
4, conf.xml
Two things need to be configured here
Configuration JDBC connection
Configuration mapper.xml
<?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="root" /> </dataSource> </environment> </environments> <!-- 注册userMapper.xml文件 --> <mappers> <mapper resource="com/mi/mapping/userMappers.xml"/> </mappers></configuration>
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; } }
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);
MyBatis implements the mapper interface through 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(); } }
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:
The following is the specific code:
1. User.java
实体类中的的get/set方法以及构造方法及toString方法就不贴了public class User { private int id; private String name; private int age;
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:
The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.
The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.
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(); }
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.
<mapper namespace="com.mi.mapper.UserMapper">
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}...
The following is the complete code: including table creation, CRUD
<mapper namespace="com.mi.mapper.UserMapper">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}
4, conf.xml
Two things need to be configured here
Configuration JDBC connection
Configuration mapper.xml
<?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="root" /> </dataSource> </environment> </environments> <!-- 注册userMapper.xml文件 --> <mappers> <mapper resource="com/mi/mapping/userMappers.xml"/> </mappers></configuration>
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; } }
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);
MyBatis implements the mapper interface through 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(); } }
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!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
