Chapter 1, Introduction to Mybatis _HelloWorld

Article directory

Introduction to Mybatis

1. Mybatis History

(1) MyBatis is an open source Apache project iBatis, which was migrated from Apache Software Foundation to Google Code in June 2010. As the development team moved to Google Code, iBatis 3.x was officially renamed MyBatis, and the code moved to Github in November 2013.

(2) iBatis comes from the combination of "internet" and "abatis", which is a persistent framework based on Java. The persistence framework provided by iBatis includes SQL Maps and Data Access Objects (DAO)

2. Introduction to Mybatis

(1) MyBatis is an excellent persistence framework that supports customized SQL, stored procedures, and advanced mapping

(2) MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets

(3) MyBatis can use simple XML or annotations to configure and map interfaces and Java POJO s (Plain Old Java Objects) into records in the database.

(4) Mybatis is a semi-automatic ORM (Object Relation Mapping) framework

3. How to download Mybatis from the official website

4. Why use Mybatis - a comparison of existing persistence technologies

(1)JDBC

(1) SQL is sandwiched in Java code block, and high coupling leads to hard-coded internal injury.

(2) Maintenance is not easy and sql changes in actual development requirements. Frequent modifications are common.

(2) Hibernate and JPA

(1) Long and complex SQL is not easy for Hibernate to handle.

(2) Internal automatic production of SQL, not easy to do special optimization

(3) Based on the fully automated framework of full mapping, it is difficult for POJO s with a large number of fields to partially map. Cause database performance degradation

(3)MyBatis

For developers, core sql still needs to be optimized by themselves

(2) Separation of sql and java coding, clear functional boundaries, one business-focused, one data-focused

Case Hello World

1. Development environment preparation

(1) Import the jar package, Mysql driver package and log4j jar package of MyBatis framework

​ myBatis-3.4.1.jar
​ mysql-connector-java-5.1.37-bin.jar
​ log4j.jarmyBatis-3.4.1.jar

(2) Import log4j configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

2. Creating database tables

CREATE TABLE tbl_employee(
   id INT(11) PRIMARY KEY AUTO_INCREMENT,
   last_name VARCHAR(50),
   email VARCHAR(50),
   gender CHAR(1)
);

insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('1','Zhang Wuji','1','Bright Top Church');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('2','Minmin Multer','0','Sheriff');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('3','Yang Zi','0','Daqiang's second daughter-in-law');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('4','Sun Li','0','Actor 2');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('5','Deng Chao','1','Actor 2');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('6','Huang Bo','1','Actor 2');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('7','Di Ali Gerba','0','Actor 2');
insert into `tbl_employee` (`id`, `last_name`, `gender`, `descr`) values('8','Qi Wei','0','Actor 2');

3. Create Java beans

package com.xxj.mybatis.beans;

public class Employee {
	
	private Integer id;
	private String lastName;
	private String gender;
	private String descr;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getDescr() {
		return descr;
	}
	public void setDescr(String descr) {
		this.descr = descr;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", descr=" + descr + "]";
	}

}

4. Create a global configuration file for Mybatis

<?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">
<!-- Mybatis Master Profile -->
<configuration>
	<!-- Configuration of database connection environment -->
	<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/study" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- Introduce SQL Mapping file,Mapper Mapping file-->
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
		
	</mappers>
	
	
</configuration>

5. Create Mybatis SQL 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="suibian">
	<select id="select" resultType="com.xxj.mybatis.beans.Employee">
	select id,last_name lastName, gender,descr from tbl_employee where id = #{id} 
		<!-- select * from tbl_employee  where id = #{id} -->
	</select>
	
	
</mapper>

6, test

@Test
	public void test() throws IOException {
		// Specify MyBatis master configuration file
		String resource = "mybatis-conf.xml";
		// Read Mybatis Master Profile
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// SqlSessionFactory Builder reads the configuration file and creates SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// Execute sql statements
		Employee employee = sqlSession.selectOne("suibian.select", 5);
		System.out.println(employee);

	}

7. Mapper Interface Development HelloWorld (Key)

(1) The Java beans used are consistent with the above

(2) Interface

public interface EmployeeMapper {

	public Employee selectById(Integer id);
	
	
}

(3) SQL 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="com.xxj.mybatis_interface.dao.EmployeeMapper">
	<select id="selectById" resultType="com.xxj.mybatis_interface.beans.Employee">
		select id,last_name,gender,descr from tbl_employee where id=#{id}
	</select>

</mapper>

(4) Global Profile

<?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">
<!-- Mybatis Master Profile -->
<configuration>
	<!-- Configuration of database connection environment -->
	<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/study" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- Introduce SQL Mapping file,Mapper Mapping file-->
	<mappers>
		<mapper class="com.xxj.mybatis_interface.dao.EmployeeMapper"/>
	</mappers>
	
	<!--
	//FALSE:
	<mappers>
		<mapper class="com.xxj.mybatis_interface.dao.EmployeeMapper.xml"/>
	</mappers>
	EmployeeMapper.xml File and interface names should be consistent
	//Using class= ", you need to remove the suffix of the filename
	//If you write EmployeeMapper.xml, the following error will be reported
	Caused by: java.lang.ClassNotFoundException: Cannot find class: 		   com.xxj.mybatis_interface.dao.EmployeeMapper.xml
	-->
	
	
</configuration>

(5) Testing

@Test
	public void test() throws IOException {
		String resource = "mybatis-conf.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		EmployeeMapper employeeDao = sqlSession.getMapper(EmployeeMapper.class);
		Employee employee = employeeDao.selectById(3);
		System.out.println(employee);
	}

3. Setting up the prompt usage and creation of Mybatis xml file

1. How to make the xml file "Alt+/" prompted

2. How to create xml with Mybatis declaration header

Tags: Mybatis xml SQL Java

Posted on Tue, 10 Sep 2019 04:50:27 -0700 by lokesh_kumar_s