catalogue
1. Prepare database information
3. Import the corresponding jar package into the pom.xml file
4. Create the corresponding entity class users
5. Complete the configuration file of mybatis
Introduction to MyBatis
Let's first understand what MyBatis is, including the following three points:
1. MyBatis is an excellent = = ORM framework that supports common sql queries, stored procedures and advanced mapping 2.MyBatis eliminates the manual setting of almost all JDBC codes and parameters and the retrieval encapsulation of the result set. 3.MyBatis can use simple XML or annotations for configuration and original mapping, and map the interface and Java POJO (Plain Old Java Objects) into records in the database. Semi automated framework. You must write sql statements.
To sum up: MyBatis is a semi-finished product that encapsulates the interaction with the database.
Basic use of MyBatis
After learning about MyBatis, of course, you should learn how to use it
1. Prepare database information
-- Create database create database mybatis_kk; -- Use database use mybatis_kk; -- Create in database users surface CREATE TABLE users(uid INT PRIMARY KEY AUTO_INCREMENT, uname VARCHAR(20), uage INT); -- Insert data into a table INSERT INTO users(uname, uage) VALUES('kk', 21); INSERT INTO users(uname, uage) VALUES('Will', 18);
2. Create a maven project
3. Import the corresponding jar package into the pom.xml file
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mybatis_k</groupId> <artifactId>mybatis_k</artifactId> <version>1.0-SNAPSHOT</version> <!--introduce jar package--> <dependencies> <!--mysql Drive dependency--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <!--mybatis Dependence of--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--Simplify in entity classes set and get Methods and tostring Method and construction method.(Installation required lombok plug-in unit)--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> </dependencies> </project>
4. Create the corresponding entity class users
@Data //set and get methods, tostring methods and constructor methods in entity classes @NoArgsConstructor //non-parameter constructor @AllArgsConstructor //Constructor for all parameters public class Users { private int uid; private String uname; private int uage; } // be careful!!!! // If there is no jar package for lombok application, you need to supplement it yourself: //set and get methods in entity classes and tostring methods and constructors
5. Complete the configuration file of mybatis
(1) Create mapper folder and MyBatis.xml file under resources, and create UsersMapper.xml file under mapper folder
(2) Configuration contents of mybatis.xml (configuration file) (mybatis will read the contents of this file to complete the function of connecting to the database.)
<?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.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_kk?serverTimezone=Asia/Shanghai" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> </configuration>
(3) Complete the mapping of sql statements, entity classes and tables in the usersmapper.xml (mapping) file.
<?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="kkk"> <!--namespace:Namespace:Its value can now be written freely. You must talk to me later dao Interface correspondence. --> <select id="selectUserById" resultType="com.kk.entity.Users"> select * from users where id=#{uid} </select> <!-- id:Unique label--> <!-- resultType: The type of result returned. mybatis The framework helps you encapsulate the results into User Type.--> <!-- #{}: = = > placeholder. And or parse the value of uid -- > </mapper>
(4) Introduce the mapping file UsersMapper.xml into the MyBatis.xml configuration file
6. Test
Create test class MyTest
public class MyTest { public static void main(String[] args) throws Exception{ //1. Read the configuration file of mybatis. Connect to database--- Reader reader = Resources.getResourceAsReader("MyBatis.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); //2. Get Session object ----- > connection object SqlSession session=sqlSessionFactory.openSession(); //3. Perform corresponding functions Users u = session.selectOne("kkk.selectUserById", 1); System.out.println(u); } }
result:
summary
Steps for using mybatis:
1. Create entity classes (Lombok simplifies set and get methods)
2. Introduce related dependencies
3. Create a configuration file for mybatis.
4. Create the mapping relationship between the mapping file sql and the entity class.
5. Register the mapping file in the mybatis configuration file.
6. Test.
Now that you have successfully completed the basic use of mybatis, you can practice CRUD operation yourself to master it
Actual use of MyBatis
Combined with dao interface
Of course, in the actual development, dao will be used to operate, and the dao interface will be combined with the mapping file.
1. Create dao interface
public interface UsersDao { public List<Users> selectAll(); public Users selectUserById(int id); public int insertUser(Users user); public int updateUser(Users user); public int deleteById(int id); }
2. Write SQL in the mapping file UsersMapper.xml
be careful!!!! The namespace should be consistent with the interface name
The id should be consistent with the method name in the 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.kk.dao.UsersDao"> <!--namespace:Namespace: And dao Interface position correspondence --> <select id="selectAll" resultType="com.kk.entity.Users"> select * from users </select> <select id="selectUserById" resultType="com.kk.entity.Users"> select * from users where uid=#{uid} </select> <insert id="insertUser"> insert into users values(#{uid},#{uname},#{uage}) </insert> <update id="updateUser"> update users set uage=#{uage} where uid=#{uid} </update> <delete id="deleteById"> delete from users where uid=#{uid} </delete> </mapper>
3. Test:
public class MyTest { private SqlSession session; @Before public void getsession() throws IOException { Reader reader=Resources.getResourceAsReader("MyBatis.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); session=sqlSessionFactory.openSession(); } @Test public void method1(){ UsersDao ud=session.getMapper(UsersDao.class); List<Users> list=ud.selectAll(); for (Users u:list){ System.out.println(u); } } @Test public void method2(){ UsersDao ud=session.getMapper(UsersDao.class); Users u= ud.selectUserById(2); System.out.println(u); } @Test public void method3(){ UsersDao ud=session.getMapper(UsersDao.class); Users u=new Users(3,"Wang Wu",22); int row =ud.insertUser(u); System.out.println("Number of rows affected:"+row); session.commit(); } @Test public void method4(){ UsersDao ud=session.getMapper(UsersDao.class); Users u=new Users(3,"Wang Wu",44); int row =ud.updateUser(u); System.out.println("Number of rows affected:"+row); session.commit(); } @Test public void method5(){ UsersDao ud=session.getMapper(UsersDao.class); int row =ud.deleteById(3); System.out.println("Number of rows affected:"+row); session.commit(); } }
Pass multiple parameters
In the above example, the methods added and modified in dao pass objects. If parameters are passed, a pit will appear
When multiple parameters are passed, the default mybatis will name these parameters: param1 param2
public int update(String uid, int umane); -->
Actually received param1,param2 update id="updateUser"> update users set uanme=#{param1} where uid=#{param2} </update>
Solution: use the custom parameter name @ Param("parameter name")
public int update(@Param("uid") String uid, @Param("uname") int uname); -->
<update id="updateUser"> update users set uname=#{uname} where uid=#{uid} </update>
Special characters
Pits also occur when special characters are used
Solution: use <! [CDATA [special characters or SQL statements]] >
<select id="selectUserByage" resultType="com.kk.entity.Users"> <![CDATA[ select * from users where uage>#{min} and uage<#{max}]]> </select>
Summary:
1.dao interface is combined with mapping file. The namespace should be consistent with the interface name The id should be consistent with the method name in the interface.
2. Of multiple parameters@ Param("parameter name") # {parameter name}
3. Escape character: <! [CDATA[sql]]>
Next, optimize mybatis~~~
Optimization of mybatis
Import db properties file
1. Define a database properties file
jdbc.drivername=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis_kk?serverTimezone=Asia/Shanghai jdbc.username=root jdbc.userpassword=123456
2. Import the attribute file into the MyBatis configuration file and use the corresponding key
<?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> <!--Import properties file--> <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!--${Gets the of the properties file key value}--> <property name="driver" value="${jdbc.drivername}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.userpassword}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UsersMapper.xml"/> </mappers> </configuration>
Import log file
1. Introduce the log jar package into pom.xml
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2. Import the log configuration file log4j.properties
log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG ### output DEBUG Logs above level to=E://logs/error.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### output ERROR Logs above level to=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3. Effect:
This can better display SQL statements!!!
Resolve the inconsistency between the column name of the database and the attribute name of the entity class
Method 1: alias the query column; Make the alias consistent with the property name
<select id="selectUserById" resultType="com.kk.entity.Users"> select users_uid uid,users_uname uname,users_uage uage from users where users_uid=#{uid} </select>
Method 2: use the resultMap tag to complete the mapping relationship between attributes and columns. (my property is the same as column because the property name corresponds to the database column name when creating the entity class)
<resultMap id="map1" type="com.kk.entity.Users" > <!--id Must write--> <id property="uid" column="uid"/> <result property="uname" column="uname"/> <result property="uage" column="uage"/> </resultMap> <!--be careful:Used resultMap Not in use resultType--> <select id="selectUserById" resultMap="map1" > select * from users where uid=#{uid} </select> <!-- id:Unique identification type: type ; Which entity class does the table map to <id Mapping relationship of primary key column="Listing" property="Attribute name"/> <result General field/> autoMapping=true Indicates automatic mapping. default true -->
affair
A transaction consists of a series of actions that either complete or do not complete.
jdbc default transaction is auto commit. Now the mybatis transaction needs to be committed manually (session.commit();).
In the above test, the submission has been realized:
Summary:
1. Import database attribute file
2. Import log file
3. Resolve the inconsistency between column name and attribute name.
(1) Alias -- consistent with property name
(2)resultMap completes column and attribute mapping
4. Transaction submission - session.commit()