MyBatis Study ( One )—Mybatis Simple introduction / Additions and deletions
01 What is? Mybatis?
Recommended reference Official documents Learn the framework .
Mybatis The original name is ibatis, Three generations later, it was renamed Mybatis.Mybatis3 Is hosted in GitHub On , attach GitHub Escrow address . The latest version is Mybatis-3.5.2, The latest version is generally not stable , here , Use Mybatis-3.5.1 To study .
MyBatis It’s an excellent Persistence layer frame , It supports Customized SQL、 stored procedure as well as Advanced mapping .MyBatis Avoided Almost all JDBC Code and Manual setting of parameters as well as Get the result set .MyBatis You can use simple XML Or annotations to configure and map native types 、 Interface and Java Of POJO(Plain Old Java Objects, Ordinary old-fashioned Java object ) For records in the database .
What is the persistence layer ?
When it comes to persistence layer , First of all, understand Persistence . Persistence is a process of data transformation between transient state and persistent state . We know , The data in the computer’s memory is lost after power failure . In order to store the data in memory persistently , We usually store this data on disk or hard disk . The persistence layer corresponds to the code structure Dao layer ,Dao The layer focuses on the operation of the database , You just need to focus on SQL Statement writing , get SQL The result of the query can be , however , In practice Dao Layers have to repeat a lot about JDBC Code for .
Persistence oriented frameworks are :
hibernate: Fully automatic ORM frame , No need to write SQL sentence , Black box operation .
Mybatis: Semi automatic ORM frame , You can customize SQL sentence ; More flexible , White box operation , be-all SQL Statements are written by developers , Can be customized to accomplish many functions .
SSH: Spring Struct1/2 Hibernate
SSM: Spring SpringMVC Mybatis
Mybatis and hibernate The difference between [ Interview questions ]:
Hibernate The advantages of :
1、hibernate yes Fully automatic ,hibernate It’s quite possible to go through Object relational model Realize the operation of database , Have complete JavaBean Object and database mapping structure to Automatic generation sql.
2、 Powerful , Good database independence ,O/R Strong mapping ability , There is very little code to write , The development speed is very fast .
3、 There is a better secondary caching mechanism , Third party caches can be used .
4、 database portability good .
5、hibernate Have a complete log system ,hibernate The logging system is very robust , It covers a wide range of , Include sql Record 、 The relationship is abnormal 、 Optimization warning 、 Cache hint 、 Dirty data warning, etc
Hibernate The shortcomings of :
1、 High learning threshold , The threshold of mastery is higher , How programmers design O/R mapping , How to strike a balance between performance and object model , And how to use it well Hibernate We need a lot of experience and ability in this area
2、hibernate Of sql Many of them are generated automatically , Can’t directly maintain sql; Although there are hql Inquire about , But it doesn’t work sql Powerful , When you see abnormal needs such as statements ,hql The inquiry should be virtual , in other words hql Queries are limited ;hibernate Although it also supports native sql Inquire about , But the development mode is similar to orm Different , You need to change your mind , So it’s not convenient to use . All in all sql In terms of flexibility hibernate Less than mybatis.
Mybatis The advantages of :
1、 Easy to use and master , Provides Automatic object binding for database queries function , And it goes on well SQL Use experience , For projects that don’t have that high object model requirements , Quite perfect .
2、sql Written in xml in , Convenient for unified management and optimization , relieve sql Coupling with program code .
3、 Provide mapping label , Support object and database orm Field relation mapping
4、 Provide object relation mapping labels , Support object relationship building and maintenance
5、 Provide xml label , Support writing dynamics sql.
6、 Velocity relative to Hibernate It’s faster .
Mybatis The shortcomings of :
1、 Association table multi time , When there are many fields ,sql A lot of work .
2、sql Database dependent , Lead to Poor database portability .
3、 because xml Inside label id Must be unique , Lead to DAO Medium method Method overloading is not supported .
4、 Object relation mapping label and field mapping label It’s just a description of the mapping relationship , The concrete implementation is still Depend on sql.
5、DAO Layers are too simple , Object assembly is a lot of work .
6、 Cascade updates are not supported 、 cascading deletion .
7、Mybatis In addition to the basic recording function of the log , Other features are much weaker .
8、 Write dynamic sql when , It is not convenient to debug , Especially when the logic is complicated .
9、 Write updates provided sql Of xml The tag function is simple , Write dynamic sql Still limited , And Low readability .
02 Mybatis Simple introduction
1. Set up the environment
1.1 Create a database
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'HooiShieh','123456'),(2,' Zhang San ','abcdef'),(3,' Li Si ','987654');
1.2 Use IDEA Create a normal Maven project
** To configure pom.xml:** add to mybatis as well as JDBC Dependence , For testing purposes , And here’s the introduction of Junit Dependence
<?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>ssm-mybatis-study</groupId>
<artifactId>Mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Mybatis</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--junit rely on -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--mybatis rely on -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--JDBC rely on -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<build>
<!-- Set up maven When exporting a project , Be able to configure (xml file ) Export with resources -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
1.3 establish POJO Entity class , Mapping database Of user surface
package com.hooi.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
// For testing purposes , rewrite toString();
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
1.4 stay resources root directory Next establish mybatis The configuration file of the environment ( It’s called mybatis-config.xml), To configure MyBatis Systematic The core Set up .
<?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 Configuration environment , There can be multiple environments default What is the default set of
environment The element body contains transaction management and connection pool configuration id Fill in the name of the environment
transactionManager A transaction manager that determines the scope and control of a transaction
dataSource Get the data source of the database connection instance type by POOLED
property Configuration of connection database
xml You are not allowed to & The symbol appears directly , Need to use & Instead of &
-->
<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?useSSL=true&useUnicode=true&charsetEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
1.5 Because each is based on MyBatis The applications are all based on one SqlSessionFactory The core of the .SqlSessionFactory Once created, it should exist for the duration of the application , There is no reason to discard it or recreate another instance . To avoid unnecessary code duplication , And in the application of multiple reconstruction SqlSessionFactory , There will be obtain SqlSessionFactory object Extract for Static methods .
package com.hooi.utils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// stay Maven in , All resource files are generally placed in resources The root directory , The files in the root directory can be obtained directly through the file name
String resource = "mybatis-config.xml";
//MyBatis Including a name Resources Tool class of , It contains some practical methods , From classpath Or other locations to load resource files more easily .
InputStream inputStream = Resources.getResourceAsStream(resource);
//SqlSessionFactory Can be passed SqlSessionFactoryBuilder get .
//SqlSessionFactoryBuilder It can be downloaded from XML Configuration file or a pre-customized one Configuration SqlSessionFactory Example .
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
1.6 To write Dao Layer mapping interface UserMapper( It’s equivalent to… In monomer hell dao Layer interface )
package com.hooi.dao;
import com.hooi.pojo.User;
import java.util.List;
public interface UserMapper {
// Get all users
public abstract List<User> selectUser();
}
1.7 Write the mapping interface corresponding to mapper The mapping file userMapper.xml, In a XML In the mapping file , You can define countless mapping statements .( The mapping file is equivalent to single hell mode dao Implementation class of ) One interface corresponds to one Mapper The 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 Labeled namespace Corresponding Mapper The class of the interface , You must specify a namespace -->
<mapper namespace="com.hooi.dao.UserMapper">
<!--select Labeled id The name of the method corresponding to the mapping interface resultType: Returns the type of result Write in the middle sql sentence -->
<select id="selectUser" resultType="com.hooi.pojo.User">
select * from user ;
</select>
</mapper>
1.8 stay mybatis-config.xml In profile Association mapping file userMapper.xml, stay configuration Add the following to the tag ( In fact, the function of this paragraph is to put mapper Associated with a database )
<!-- Association mapping file -->
<mappers>
<mapper resource="com/hooi/dao/userMapper.xml"/>
</mappers>
2. test
2.1 stay maven Of test Under the table of contents To write Corresponding Test class
package com.hooi.dao;
import com.hooi.pojo.User;
import com.hooi.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void selectUser(){
//1. Get sqlSessionFactory object
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
/*2. adopt sqlSessionFactory Object's openSession() Create a sqlSession.
SqlSession It completely includes database oriented execution SQL All methods required for the command .
Can pass SqlSession Instance to directly execute the mapped SQL sentence .
*/
SqlSession sqlSession = sqlSessionFactory.openSession();
/*
3. adopt sqlSession get mapper object , The parameter is the interface class corresponding to the mapping file class object
It can be understood as by giving sqlSession Passing in the interface class class Object to get the implementation class of the interface
*/
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4. adopt mapper Object to perform operations ;
List<User> users = mapper.selectUser();
// Get the result set
for (User user : users) {
System.out.println(user);
}
}
}
Running results :
——
03 Mybatis Operating the database
Need here Be careful Yes. , About Additions and deletions need Commit transaction .
The type of parameter passed in , Basic types Sure Omit Parameter type parameterType Writing , Reference type data must write .
Type of return value , The basic type can omit the return value type resultType Writing , Reference type data must write .
mapper Interface source code :
package com.hooi.dao;
import com.hooi.pojo.User;
import javax.jws.soap.SOAPBinding;
import java.util.List;
public interface UserMapper {
// Get all users
public abstract List<User> selectUser();
// according to id Find user
public abstract User selectUserById(int id);
// Add users
public abstract int addUser(User user);
// according to id Delete user
public abstract int delUserById(int id);
// Update user data
public abstract int updateUser(User user);
}
mapper Mapping file source code :
<?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 Labeled namespace Corresponding Mapper The name of the interface -->
<mapper namespace="com.hooi.dao.UserMapper">
<!--select Labeled id The name of the method corresponding to the mapping interface parameterType Corresponding to the type of the parameter passed in resultType: Returns the type of result stay select In the middle of the tag sql sentence -->
<select id="selectUser" resultType="com.hooi.pojo.User">
select * from user
</select>
<select id="selectUserById" parameterType="int" resultType="com.hooi.pojo.User">
select * from user where id=#{id}
</select>
<!-- Reference object needs to set parameter type parameterType Properties of Properties of reference objects can be used directly #{ Property name }-->
<insert id="addUser" parameterType="com.hooi.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="delUserById" >
delete from user where id=#{id}
</delete>
<update id="updateUser" parameterType="com.hooi.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
</mapper>
Test source :
package com.hooi.dao;
import com.hooi.pojo.User;
import com.hooi.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
/*
Each thread should have its own SqlSession example .
SqlSession Is not thread safe , So it can't be shared , So its best scope is request or method scope .
Never put SqlSession Instance references are placed in the static domain of a class , Not even instance variables of a class .
*/
@Test
public void selectUser(){
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();.
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void selectUserById(){
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(3);
System.out.println(user);
}
@Test
public void addUser(){
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int updateRows = mapper.addUser(new User(4, "hooi", "666666"));
if (updateRows>0){
System.out.println(" Add success ");
session.commit();// Commit transaction
}
session.close();// Closing transaction
}
@Test
public void delUserById(){
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int updateRows = mapper.delUserById(4);
if (updateRows>0){
System.out.println(" Delete successful ");
session.commit();
}
session.close();
}
@Test
public void updateUser(){
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int updateRows = mapper.updateUser(new User(1, "HooiShieh", "123456"));
if (updateRows>0){
System.out.println(" The update is successful ");
session.commit();
}
session.close();
}
}
test result :
1. Get test results for all users
2. according to id Find the user’s test results
3. Add user test results
4. according to id Delete user test results
5. Update test results of user data