MyBatis first day of study

Introduction The mybatis framework is a Java...
What is a framework?
What is an ORM framework?
Disadvantages of using JDBC to complete ORM operations?
concept
Development steps for mybatis
mybatis development steps supplement
Introduction

The mybatis framework is a Java-based persistent layer framework that supports custom frameworks. This article is mainly to understand the mybatis framework, to give a simple introduction to the mybatis framework, to understand how the mybatis framework achieves the operation of the Java persistence layer, and what is the advantage over the traditional jdbc operation of the mybatis framework

Knowledge is shared, but we want to reload it with the original address.

Article Directory

What is a framework?

The semi-finished product of the software solves the universality problem in the software process, simplifies the development steps and provides the efficiency of development.

What is an ORM framework?

  • ORM(Object Relational Mapping) object-relational mapping, which maps one object in a program to one row of data in a table
  • The ORM framework provides mapping relationships between persistent classes and tables, persisting queues to databases at run time by referencing file information

Disadvantages of using JDBC to complete ORM operations?

  • There is a lot of redundant code (load drivers, get connections, release connections)
  • Manual Creation Connection.Statement etc.
  • Manually encapsulate result sets as entity queues
  • Inefficient queries, no database access optimization (Not Cache)
MyBatis Framework

concept

  • MyBatis was originally an open source project of the Apache Software Foundation, iBatis, which was migrated from apache asoftware foundation to Goole Code in 2010 and renamed MyBatis, to GitHub in November 2013
  • Mybatis is an excellent Java-based persistent framework that supports custom SQL, stored procedures, and advanced mappings
  • Mybatis encapsulates the original JDBC operations, eliminating almost all JDBC code, allowing developers to focus only on SQL itself
  • MyBatis can use simple XML or Annotation to configure execution of SQL and automatically complete ORM operations to return execution results

Development steps for mybatis

Core Configuration

Build the maven project before you startPom.xmlIn configuration information

<?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>per.leiyu</groupId> <artifactId>Mybatis1</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <!--Mybatis Core Dependency --> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- Import mysql Driver dependency of--> <!-- Because of our mybatis Framework is the framework for database operations,So we need to import the drive dependencies of the database we're working on--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> </dependencies> <build> <plugins> <plugin> <!--To configure jdk --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <target>1.8</target> <source>1.8</source> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>

Except inPom.xmlWrite the configuration in, and also provide a configuration file for mybatis (write detailed configuration information about the database and mybatis) in the configuration file, usually for name sake - mybatis-config.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"> <!--Above is the header of mybatis configuration file--> <configuration> <!--Here are the core configurations for mybatis Hierarchy and label names are fixed, and you can follow this template if you want --> <environments default="leiyu_mybaits"> <!--Configuration and database related information--> <environment id="leiyu_Mybaits "><!--Equivalent to having a name for us in the environment configuration, and then we can default to the information we configured by default above--> <!--Transaction Control Type--> <transactionManager type="JDBC"></transactionManager> <!--Configure database connection information--> <!--This is a much easier way to import connection pools by configuring the type of type than before--> <dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory"> <property name="driver" value="com.mysql.jdbc.Driver" /> <!--Escape Characters &Methods are illustrated in the tab below--> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8"/> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!--Register our mapper file--> <mappers> <mapper resource="UserDaoMapper.xml"/> </mappers> </configuration>

Create database, create table

create datebase mybatis default charset = uff8; use mybatis; create table t_user( id int parmary key auto_increment, username varchar(50), passward varchar(50), gender tinyint, regist_time datetime )defaault charset=utf8;
Create databases and tables using mysql integrated in the database visualizer or IDea

Create Entity Class

  • Creating an entity class User corresponds to t_in the databaseUser table
package per.leiyu; import java.util.Date; /** * @author Thunderstorm * @date 2020/6/11 10:03 */ public class User { private Integer id; private String username; private String passward; private Boolean gender; private Date registTime; public User() { super(); } public User(Integer id, String username, String passward, Boolean gender, Date registTime) { this.id = id; this.username = username; this.passward = passward; this.gender = gender; this.registTime = registTime; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", passward='" + passward + '\'' + ", gender=" + gender + ", registTime=" + registTime + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassward() { return passward; } public void setPassward(String passward) { this.passward = passward; } public Boolean getGender() { return gender; } public void setGender(Boolean gender) { this.gender = gender; } public Date getRegistTime() { return registTime; } public void setRegistTime(Date registTime) { this.registTime = registTime; } }

Define the Dao interface

  • That is, the interface of the sql statement that we want to execute
package per.Dao; import per.leiyu.User; /** * @author Thunderstorm * @date 2020/6/11 10:06 */ public interface UserDao { User queryUserById(Integer id); }

EstablishUserDaoMapper.xml

  • Tell mybatis what the sql statement executed by the method in the UserDao interface is, what the return value is, and how the required parameters are provided to mybatis

  • Instead of creating entity classes for abstract interfaces in the dao layer, we use xml files to manage jdbc operations in the mybatis framework

  • The mybatis framework simplifies our development by encapsulating the original registration drivers, getting connections, freeing resources, etc. We can only configure and invoke the encapsulated methods to operate jdbc (including optimizing database operations).

<?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"> <!-- Indicate the xml File is used to describe that dao Interface--> <mapper namespace="per.Dao.UserDao"> <!-- description method --> <!-- id:Describes the method in that interface resultType:The type of playback result for the described method #:Represents the first parameter in the interface,Then the second parameter of the parameter in the interface is used# representation --> <select id="queryUserById" resultType="per.leiyu.User"> select * from t_user where id =# </select> </mapper>
  • Looking closely at this configuration file, you will see that we create the dao implementation class, execute sql statements, encapsulate the result set as user objects, and give mybatis the solution for us

  • We have written the mapper configuration file and need to enable the mapper configuration file we have written in the mybatis-config configuration file

Create Test Class

package per.leiyu.UserDao; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import per.Dao.UserDao; import per.leiyu.User; import java.io.IOException; import java.io.InputStream; /** * @author Thunderstorm * @date 2020/6/11 10:21 */ public class TestUserDao { public static void main(String[] args) throws IOException { //1. Load Profile InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); //2. Build objects for SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. Create SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //4. Obtaining DAO implementation class objects through SqlSession //Previously, we said that the implementation class of DAO was not something we did personally, but that mybatis dynamically made for us through reflection in the early memory of the configuration file. //We can't see this class, but we need it to do our DAO's work UserDao mapper = sqlSession.getMapper(UserDao.class); User user1 = mapper.queryUserById(1); User user2 = mapper.queryUserById(1); System.out.println(user1); System.out.println(user2); } }
Get the results from the database (indicating we succeeded with mybatis)

From the test class above, we can see that we get a User object by the id value, so how does mybatis encapsulate the result set as a User object?

Question: How does mybatis encapsulate result sets as objects?

  • Use the same name policy
How does mybatis encapsulate result sets as objects?

Since regist_The property names and column names of time and registTime are different, resulting in no assignment of related data in the query result set.

The solution is to use aliases when querying, which are the property names you want in the java class.

select id,username,passward,gender,regist_time as registTime from t_user where id=#

mybatis development steps supplement

SolveMapper.xmlRead problems stored in paths other than resources

In mybatis-Config.xmlPath to modify mapper file in file

stayPom.xmlThe file is last tagged so that it can be copied to classes and read normally when the program is running

<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>*.xml</inclued> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources>

Solve database-related configuration issues

Previously, we encapsulated database-related configurations in mybatis's configuration file, because mybatis is really meant to help us operate the database, but the details about the database's account password are often modified, so we expect to separate the detailed configuration of the database from the configuration of mybatis.

Add the configuration of the database to the configuration file:jdbc.properties

#jdbc.properties jdbc.driver =com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true jdbc.username=root jdbc.passward=123456

Modified mybatis-Config.xmlConfiguration

Configuration files that need to import dataJdbc.propertiesAnd assign values to the xml configuration file

The assignment here uses $

<?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"> <!--Above is the header of mybatis configuration file--> <configuration> <!--Here are the core configurations for mybatis Hierarchy and label names are fixed, and you can follow this template if you want --> <!--Introducing resource filesJdbc.properties--> <properties resource="jdbc.properties" /> <environments default="leiyu_mybaits"> <!--Configuration and database related information--> <environment id="leiyu_Mybaits "><!--Equivalent to having a name for us in the environment configuration, and then we can default to the information we configured by default above--> <!--Transaction Control Type--> <transactionManager type="JDBC"></transactionManager> <!--Configure database connection information--> <!--This is a much easier way to import connection pools by configuring the type of type than before--> <dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory"> <!--Index to using a $placeholderJdbc.propertiesSpecific content in configuration file--> <property name="driver" value="$" /> <!--Escape Characters &Methods are illustrated in the tab below--> <property name="url" value="$"/> <property name="username" value="$" /> <property name="password" value="$" /> </dataSource> </environment> </environments> <!--Register our mapper file--> <mappers> <mapper resource="per/Dao/UserDaoMapper.xml"/> </mappers> </configuration>

So mybatis-Config.xmlConfiguration of database inJdbc.proertiesAssociated,Jdbc.propertiesConfiguration changed at mybatis-Config.xmlRelated configurations will also change in

Type Alias (give an alias to an entity class)

Previously, we would use mybatis to manipulate the return type of the database in the result set, wrapping it as the type of one of our entity classes

Before aliasing, we need to write the full path of this entity class

Write the full path of the entity class each time to avoid writing a lot of hot redundant code. We want to give the entity class an alias, so mybatis-Config.xmlConfiguration in

<configuration> <typeAliases> <!--Choose one of the definitions here--> <!-- <typeAlias type="per.leiyu.User" alias="User" />--> <!--Automatically scans package names, defau lt ing to the full path alias of all entity classes in the package by their own names--> <package name="per.leiyu"/> </typeAliases> </configuration>

Create log4j configuration file (create log file)

stayPom.xmlImport Dependencies in

<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>

Create a configuration file for log4j: the name must be log4j.properties

#Global logging configuration log4j.rootLogger=DEBUG,stdout #Mybatis logging configuration log4j.logger.org.mybatis.example.BlogMapper=TRACE #Console output log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p[%t] - %m%n
The project structure is attached at the end Project structure

12 June 2020, 21:34 | Views: 8977

Add new comment

For adding a comment, please log in
or create account

0 comments