Basics of a mybatis

A, Mybatis introduction

  • What is mybatis?

MyBatis is an excellent persistence framework that supports custom SQL, stored procedures and advanced mappings. MyBatis avoids almost all JDBC code and manual setting parameters and obtaining the result set. MyBatis can use simple XML configuration and mapping annotations or native types, interfaces and Java POJO (Plain Old Java Objects, plain old Java object) is recorded in the database.
Mybatis is sql-oriented persistence layer framework, which encapsulates the process JDBC database access, in the development, only need to focus assembled sql statement itself, and all the other complex process to mybatis to complete.

  • Why study Mybatis?

1. The most mainstream of the persistence layer framework to hibernate and mybatis two kinds, and domestic companies currently use mybatis framework of the majority.

2.HIbernate learning and mastery of the relatively high threshold, hibernate in how to design the high threshold O / R mapping, how to weigh the balance between performance and object model, and how to use good HIbernate cache and data loading strategy requires a lot of time and the accumulation of experience.

3.hibernate in sql optimization, the query will list all fields check out, this performance will be consumed, although you can also specify hibernate query field, but doing so would undermine the development of simple and hibernate.

Second, the entry Mybatis

Project build process
  • 1. Create a plain Java project, import the appropriate JAR package
  • 2. Create the POJO class
  • 3. Configure the log file log4j.properties
  • 4. Create a configuration file SqlMapConfig.xml
  • 5. Configure sql query mapping file user.xml
  • 6. Develop and test class mybatiesTest.java load map file
1. Create a project directory structure shown in Figure
  • The jar package introduced under-cladding lib
    Here Insert Picture Description
2. Create the POJO class
package mybatis.pojo;

import java.util.Date;

public class User {
private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址

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 getSex() {
	return sex;
}

public void setSex(String sex) {
	this.sex = sex;
}

public Date getBirthday() {
	return birthday;
}

public void setBirthday(Date birthday) {
	this.birthday = birthday;
}

public String getAddress() {
	return address;
}

public void setAddress(String address) {
	this.address = address;
}

@Override
public String toString() {
	return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
			+ address + "]";
}

}

3. Configure the log file log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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

4. Create a configuration file SqlMapConfig.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>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
	<environment id="development">
		<!-- 使用jdbc事务管理 -->
		<transactionManager type="JDBC" />
		<!-- 数据库连接池 -->
		<dataSource type="POOLED">
			<property name="driver" value="com.mysql.jdbc.Driver" />
			<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
			<property name="username" value="root" />
			<property name="password" value="123" />
		</dataSource>
	</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<mapper resource="mybatis/user.xml"></mapper>
</mappers>
</configuration>

5. Configure sql query mapping file user.xml
<?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">
<!--namespace命名空间,用于隔离sql语句,后续有重要作用 -->
<mapper namespace="user">
<!--id是sql语句的唯一标志 parameterType入参的数据类型 resultType是返回的数据类型 -->
<select id="getUserById" parameterType="int" resultType="mybatis.pojo.User">
	select*from user where id=#{id2}
</select>
<!-- #{}:占位符 -->
<select id="getUserByUserName" parameterType="String" resultType="mybatis.pojo.User">
	select*from user where `username` LIKE #{name}
</select>
</mapper>

6. Develop and test class mybatiesTest.java load map file
package mybatis.test;
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;
import org.junit.Test;
import mybatis.pojo.User;

public class mybatiesTest {
@Test
public void testGetUserByid() throws Exception {
	// 创建SqlSessionFactoryBuilder对象
	SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
	// 查找配置文件创建输入流
	InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
	// 加载配置文件,创建SqlSessionFactory对象
	SqlSessionFactory sqlSessionFactory = sfb.build(inputStream);
	// 创建SqlSession对象
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// 执行查询,参数一:要查询的statementId ,参数二:sql语句入参
	User user = sqlSession.selectOne("user.getUserById", 1);
	// 输出查询结果
	System.out.println(user);
	// 释放资源
	sqlSession.close();
}
}

The test results themselves to see the pictures.

Second, to strengthen the foundation part

  • Extraction Tools
package mybatis.utils;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryUtils {
// 创建SqlSession对象
private static SqlSessionFactory sqlSessionFactory;
static {
	try {
		// 创建SqlSessionFactoryBuilder对象
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
		// 查找配置文件创建输入流
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 加载配置文件,创建SqlSessionFactory对象
		sqlSessionFactory = ssfb.build(inputStream);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

public static SqlSessionFactory getSqlSessionFactory() {
	return sqlSessionFactory;
}
}
1. query operation, the fuzzy set of the same name in the inquiry data
第一种:
<select id="getUserByUserName" parameterType="String" resultType="mybatis.pojo.User">
	select*from user where `username` LIKE #{name}
</select>
第二种:
<select id="getUserByUserName" parameterType="String"
	resultType="mybatis.pojo.User">
	select*from user where username LIKE '%${value}%'
	<!--${} :是字符串拼接指令,如果入参是普通类型,{}内部只写value -->
</select>
  • Test Methods
@Test
public void testGetUserByName() {
	// 获取SqlSessionFactory
	SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
	// 创建sqlSession
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// 查询列表使用API为selectList方法得到集合,下面是第一种
	List<User> list = sqlSession.selectList("user.getUserByUserName", "%张%");
   //第二种
   //List<User> list = sqlSession.selectList("user.getUserByUserName", "张");
	
	//遍历集合
	for (User user : list) {
		System.out.println(user);
	}
	//关闭sqlSession,释放资源
	sqlSession.close();
}
2. insert

Mapping sql statement

 <!--插入用户的操作  -->
<insert id="insertUser" parameterType="mybatis.pojo.User">
<!--  
selectKey:主键返回
keyProperty:user中主键的属性
resultType:主键的数据类型
order:指定selectKey何时执行,after在插入数据后进行执行
-->
<selectKey keyProperty="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
insert into `user`(`username`,`birthday`,`sex`,`address`)
values(#{username},#{birthday},#{sex},#{address})
</insert>

--上面的查询主键返回,在mybatis中可以简写成如下即可。
<insert id="insertUser" parameterType="mybatis.pojo.User" useGeneratedKeys="true" keyProperty="id">

Write test classes, be sure to submit the transaction.

@Test
public void testInsertUser() {
	// 获取SqlSessionFactory
	SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
	// 创建sqlSession
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// new 一个User对象,并向其中存入一条数据
	User user = new User();
	user.setUsername("张飞");
	user.setSex("1");
	user.setBirthday(new Date());
	user.setAddress("上海体育学院");
	// 插入方法insert
	int time=sqlSession.insert("user.insertUser", user);
	//测试插入记录的ID
	System.out.println(time);
	// 进行数据提交事务
	sqlSession.commit();
	// 释放资源
	sqlSession.close();
}
3. Modify the user update
<!--更新用户 -->
<update id="updateUser" parameterType="mybatis.pojo.User" >
update `user` set `username`=#{username} where `id`=#{id}
</update>
@Test
public void testUpdateUser() {
	// 获取SqlSessionFactory
	SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
	// 创建sqlSession
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// new 一个User对象,并向其中存入一条数据
	User user = new User();
	user.setId(27);
	user.setUsername("张飞2");
	// 插入方法insert或者update都可以
   sqlSession.update("user.updateUser", user);
	// 进行数据提交事务
	sqlSession.commit();
	// 释放资源
	sqlSession.close();
}
4. Delete User Information
	<!--删除用户 -->
	<delete id="deleteUser" parameterType="int">
	delete from `user` where `id`=#{id}
	</delete>
	@Test
	public void testDeleteUser() {
		// 获取SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
		// 创建sqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 删除方法delete
    sqlSession.delete("user.deleteUser", 27);
		// 进行数据提交事务
		sqlSession.commit();
		// 释放资源
		sqlSession.close();
	}

Four, mybatis architecture and Detailed

Here Insert Picture Description

mybatis Configuration
  • SqlMapConfig.xml, mybatis this file as a global configuration file to configure the mybatis operating environment and other information.
  • mapper.xml sql file that is mapped files, database tables on the number of how many mapper.xml file is created, the configuration file in the sql statement the database. All you need to load and configure the file path in SqlMapConfig.xml in.
  • Environment configuration information configured by mybatis SqlSessionFactory i.e. session factory, i.e. a session created by the session SQLSESSION plant, database operations required by sqlSession. We recommend sqlSession applications in vivo.
  • mybatis underlying actuator Executor customized database interface operation, there are two interfaces implemented Executor, is a basic actuator, an actuator is a buffer.
  • Mapped Statement mybatis is a bottom package object that wraps mybatis sql configuration information and mapping information. mapper.xml a file corresponding to a sql Mapped Statement objects, sql Mapped statement that is the id of the id.
  • Mapped Statement sql performed on the input parameters are defined, including the HashMap, basic types, pojo, Executor java object by mapping Mapped Statement before performing sql sql inputted to the input parameter is mapped jdbc programming parameters provided preparedStatement.
  • Mapped Statement sql execution result output is defined, comprising the HashMap, basic types, pojo, Executor output by Mapped Statement mapped to java objects after execution sql, the mapping process is equivalent to the output of the analysis process jdbc programming process results .
mybatis and essential difference between hibernate and scenarios
  • hibernate

It is a standard framework for ORM (object-relational mapping). High barriers to entry, the program does not need to write sql, sql statement is automatically generated.
To optimize the sql statements modify more difficult.   
Scenario:
not much applicable to the changing needs of small and medium sized projects, such as: back-end management system, erp, orm, OA, etc.

  • mybatis

Focus is sql itself, programmers need to write your own sql statement, sql modify and optimize more convenient. mybatis is not a complete ORM framework, although programmers write their own sql, mybatis can also implement the mapping (mapping input, output mapping).
Scenario:
 more applicable to the changing needs of the project, such as: Internet projects.
Note: Enterprise technology selection, low cost high return as the principle of technology selection, selected according to the technical strength of the project team.

Guess you like

Origin blog.csdn.net/xiayubao7788/article/details/92383116