MyBatis learning summary
- MyBatis learning summary
- Introduction of MyBatis
- MyBatis framework environment construction and environment introduction
- MyBatis project environment construction
- Specific operation of MyBatis
- There are three query methods
- List
- object
- Map
- Parameter passing operation
- Directly by value
- Object by value
- The Map by value
- Mapper agent add, delete, modify, and query operations
- insert
- Modify the
- delete
- There are three query methods
- Note for use with MyBatis
Summary of learning MyBatis process
Introduction of MyBatis
MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.
This is an introduction to Apache’s official documentation, from which we can get some information
- MyBatis is a persistent layer framework
- JDBC Code and setting parameters and fetching result sets are almost eliminated
- Configure and map primitive types, interfaces, and Java POJOs to records in the database through XML or annotations
In the early stage, we can intuitively feel the traversal brought by the second and third points. Just think about the JDBC we practiced in the learning process before, we usually need to write the connection of the database, create the Statement with the connection, obtain the result set, and finally traverse the data one by one from the result set. During the most troublesome is to set parameters and receive parameters, a few field name is ok, once the field name, table more do not want to write JDBC, so in the early learning MyBatis when we can experience the framework to bring us some convenience.
MyBatis framework environment construction and environment introduction
Before learning we need to download MyBatis:Github.com/mybatis/myb…After downloading, open the folder, we can see the first JAR package:Mybatis — 3-5-2. Jar — mybatis — 3-5-2. Jar — mybatis — 3-5-2
After importing the jar package described above into the project, the preparation of the framework environment construction of MyBatis is completed (if you want to use the log, you also need to download the log4j dependency package) and then enter the environment construction of the project
MyBatis project environment construction
New projectMyBatis1
Layer the project SRC asentity
,mapper
andtest
First we create a JavaBean fileAccount
inentity
Directory:MyBatis (MyBatis, MyBatis, MyBatis, MyBatismybatis-config.xml
<! DOCTYPEconfiguration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<! The content of element type "configuration" must match "(properties? ,settings? ,typeAliases? ,typeHandlers? ,objectFactory? ,objectWrapperFactory? ,reflectorFactory? ,plugins? ,environments? ,databaseIdProvider? ,mappers?) ". Means that the tags in the "Configuration" tag must be written in the following order: Properties Settings typeAliases typeHandlers objectFactory ObjectWrapperFactory reflectorFactory plugins environments databaseIdProvider mappers can see that the properties tag must be placed first -->
<! -- Can be configured externally and can be dynamically replaced. This is used to read the JDBC connection parameter of jdbc.properties.
<properties resource="jdbc.properties"/>
<! -- Database environment -->
<! Create an alias for the entity class -->
<typeAliases>
<! Create an alias for the entity class.
<! -- <typeAlias type="com.lyl.mybatis.entity.Account" alias="a"/>-->
<! The package alias can be set directly when the entity class is multiple, and the return type can be written directly to the class name.
<package name="com.lyl.mybatis.entity"/>
</typeAliases>
<! -... -->
<environments default="MySQL">
<environment id="MySQL">
<! MyBatis specifies the same transaction management system as JDBC.
<transactionManager type="JDBC"/>
<! The connection pool principle is used in the bottom layer.
<dataSource type="POOLED">
<! Jdbc.properties -->
<property name="driver" value="${m_driver}"/>
<property name="url" value="${m_url}"/>
<property name="username" value="${m_user}"/>
<property name="password" value="${m_pwd}"/>
</dataSource>
</environment>
</environments>
<! -... -->
<! -- Scan mapping files -->
<mappers>
<mapper resource="com/lyl/mybatis/mapper/Account.xml"/>
</mappers>
</configuration>
Copy the code
Mybatis -config. XML file is the core configuration file of Mybatis. SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory The core of our operation must be around the SqlSessionFactory stuff, which will be discussed later. So write MyBatis core configuration is not good, after the database connection that add, delete, change, check operation SQL statement where? Uninstall mybatis-config. XML directly. At the end of the code above you can see the
The real power of MyBatis lies in its statement mapping, which is its magic. Because of its exceptional power, the MAPper’s XML file is relatively simple. If you compare it to JDBC code with the same functionality, you’ll immediately see that nearly 95% of the code is saved. MyBatis aims to reduce usage costs and allow users to focus more on SQL code.
The
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespance="com.lyl.mybatis.mapper.Account">
<! -- Namespance: namespace for finding the correct SQL mapping statement in Java code -->
<! -- public Account listAccount(){} -->
<select id="listAccount" resultType="account">
select * from account
</select>
</mapper>
Copy the code
Public Account listAccount(){} public Account listAccount(){} public Account listAccount(){} public Account listAccount(){} Then the basic environment construction of MyBatis project has been completed, so make a summary:
- Import core packages, dependencies, database core packages, layer projects, and create Javabeans
- Write the core configuration of MyBatis
mybatis-config.xml
- Write SQL mapping files
AccountMapper.xml
At the time of writing the configuration file, we will write a lot of configuration information, there may appear the advantage of the MyBatis is insufficient, this and we write the same JDBC, code appears to be no less, then we will feel the convenience of MyBatis from the test, at the same time must not be config file to get dizzy, Just remember the basic three steps
Specific operation of MyBatis
Mysql > create test.java from Test package to Test MyBatis.
- SqlSessionFactoryBuilder
- SqlSessionFactory
- SqlSession
SqlSessionFactory: SqlSessionFactory: SqlSessionFactory: SqlSessionFactory: SqlSessionFactory SqlSession is used to implement the specific operation, so that the relationship between the three is clear, let’s test before preparation:
public static void main(String[] args){
String resource = "mybatis.xml";
InputStream inputStream = null;
SqlSession sqlSession = null;
try {
Mybatis provides the Resources class to obtain mybatis core configuration file input stream
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory = sqlSessionFactory = sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3. Get Session
sqlSession = sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession! =null){ sqlSession.close(); }}}Copy the code
Above are the steps to get the SqlSession, followed by the query method
There are three query methods
SqlSession provides three query methods to facilitate our simple query operation, but also corresponding to the three query result set is not the same
List
Write SQL statements in accountmapper.xml
<select id="listAccount" resultType="account">
select * from account
</select>
Copy the code
Once written, we start executing the Java code
List<Account> list = sqlSession.selectList("com.lyl.mybatis.mapper.Account.listAccount");
System.out.println(list);
Copy the code
Print the result
[Account{id=1, username='Joe', balance=1000.0}, Account{id=3, username='Cathy', balance=2000.0}, Account{id=4, username='Daisy', balance=4000.0}, Account{id=5, username='when eight', balance=3000.0}]
Copy the code
So if we look at the Java code and we see that it’s going to return a List, so these two methods are pretty much the same except they’re going to return a different type, and just to mention this, The above AccountMapper. XML < mapper namespace = “. Com. Lyl. Mybatis mapper. The Account “> the role of the namespace is reflected in this, Ensure that our SqlSession maps and operates on SQL statements based on the NAMESPACE and id of each SQL action label
object
<select id="selectOne" resultType="account">
select * from account where id=3
</select>
Copy the code
Executing Java code
Account account = sqlSession.selectList("com.lyl.mybatis.mapper.Account.selectOne");
System.out.println(account);
Copy the code
Print the result
Account{id=3, username='Cathy', balance=2000.0}
Copy the code
Map
<select id="selectMap" resultType="map">
select * from account
</select>
Copy the code
Executing Java code
Map<Object, Object> account = sqlSession.selectMap("com.lyl.mapper.AccountMapper1.selectMap"."id");
System.out.println(account);
Copy the code
Print the result
{1={balance=1000.0, id=1}, username= username},3={balance=2000.0, id=3, username=王五}, 4={balance=4000.0, id=4}, username= "",5={balance=3000.0, id=5}}Copy the code
Do not change generics in Map! Don’t change! Don’t change! In case of any error, I will not be responsible for it. There are two parameters passed in Map. It should not be difficult to infer the relationship between the two parameters and the meaning of id parameter from the result set. List is recommended among the three methods, because List can basically do what Map can do. Simple queries do not need to use Map features, and Map may also be used in the later development, so you need to understand and use it by yourself.
Parameter passing operation
Our SQL statement is impossible to write dead, we need to carry out the specified SQL operation according to our requirements, at this time, we need to transfer parameters, MyBatis is the DECOUPLING of SQL and Java code, but also to provide the corresponding interface for our parameter transfer, which can be roughly divided into three ways of value transfer.
Directly by value
MyBatis has some built-in Java type aliases that can be found in the API. You can simplify the fully qualified class names in the configuration file through aliases, which are some basic data types and wrapper classes.
Object by value
MyBatis will transfer the value of the object according to the corresponding statement format of THE SQL mapping file during processing. This method is really convenient in handling single table query, but it will be very limited in handling multiple tables. An object cannot contain all the fields of multiple tables, so what is the solution? So we’re going to use Map to pass values.
The Map by value
Map<String,Object> map = new HashMap<>(); // Create Map generics with Key--String, Value--Object
// Push data into map
map.put("id".1);
map.put("username"."Zhang");
The value of the SQL statement of the SQL mapping file is determined by key
Account account = sqlSession.selectOne("com.lyl.mapper.AccountMapper2.selectOne3", map);
Copy the code
Mapper agent add, delete, modify, and query operations
UpDate and query operations by the same token, the only way is different, but the same is operating by SqlSession objects, incoming parameters at most one, so that caused the limitations, and we did not write to the usual database operation interface, caused the late code maintainability is low, so start learning Mapper agent to solve the problem.