Today I learned myBatis framework, briefly record myBatis first introductory case, the goal is to use MyBatis as a persistence layer framework, execute SQL statements to query data and get result sets
Basic steps:
- Physical modeling
- Logical modeling
- Introduction of depend on
- Create a persistence layer interface
- Joining the Logging Framework
- Global file Configuration
- Mapping File Configuration
- The test program
1. Physical modeling
Create database mybatis-example, table T_emp, add a row of data.
CREATE DATABASE `mybatis-example`;
USE `mybatis-example`;
CREATE TABLE `t_emp`(
emp_id INT AUTO_INCREMENT,
emp_name CHAR(100),
emp_salary DOUBLE(10.5),
PRIMARY KEY(emp_id)
);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
Copy the code
2. Logical modeling
Create an entity class Employee under the POJO package, introduce lombok dependencies, and add annotations.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer empId;
private String empName;
private Double empSalary;
}
Copy the code
The use of lombok
First, install the plugin. Search for Lombok pepper in the Marketplace in Settings and click install
The second step, importing the dependency, is in the POM.xml file
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
Copy the code
3. Introduce dependencies
Lombok dependencies have already been introduced in logical modeling, but the following dependencies need to be introduced in this case
<! Mybatis core -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<! -- Junit test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<! -- MySQL driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
Copy the code
4. Create a persistence layer interface
The persistence layer interfaces are the Dao interfaces we used before, but we used to name them Mapper interfaces when using the Mybatis framework. Since the persistence layer is connected to the database, we can explain the introduction of mysql dependencies.
package Mapper;
import pojo.Employee;
public interface EmployeeMapper {
/ * * /
void insertEmployee(Employee employee);
/ * delete * /
void deleteEmployee(Integer empId);
/* Change the name according to the ID */
void updateEmployee(Integer empId,String empName);
Search for * / / *
Employee selectEmployee(Integer id);
}
Copy the code
Note that we create an interface, not an implementation class, to solve the problem of redundancy and coupling of the persistence layer code.
5. Add the logging framework
Since Mybatis uses log4j for logging printing, we must import log4J dependencies and provide log4J configuration files in order to observe logging inside Mybatis
5.1 Log4J Dependencies
Introduce log4j dependencies in POM.xml
<! -- log4j log -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Copy the code
5.2 Log4J Configuration file
The first, XML configuration, creates log4J.xml under the classpath, resources
<! DOCTYPElog4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<! ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender ConsoleAppender
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<! -- Code of output log -->
<param name="Encoding" value="UTF-8" />
<! -- Specify the format of log output -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<! Debug info Warning Error -->
<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>
Copy the code
The second, properties configuration, creates log4j.properties under the classpath, resources
# Log level of output
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#[%-5p] %t %l %d %rms:%m%n
#%d{yyyy-MM-dd HH:mm:ss,SSS\} %-5p [%t] {%c}-%m%n
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %t %l %d %rms:%m%n
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=D:\\idea_project\\mybatis.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS\} %-5p [%t] {%c}-%m%n
Copy the code
Overview of logs
1. Log level
ATAL >ERROR >WARN >INFO >DEBUG, printed from left to right in more and more detail
2. STDOUT
B: Standard output. For Java programs, printing to standard output is printing to the console.
6. Global configuration file
In the classpath, resources, create mybatis-config.xml.
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<! POOLED: built-in connection pool 2. UNPOOLED: no connection pool 3. JNDI -->
<property name="username" value="root"></property>
<property name="password" value="888888"></property>
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"></property>
</dataSource>
</environment>
</environments>
<mappers>
<! --resource= mapping path -->
<mapper resource="mappers/EmployeeMapper.xml"/>
</mappers>
</configuration>
Copy the code
7. Map the configuration file
A mapping profile corresponds to a Mapper interface, and a sublabel in the mapping profile corresponds to a method in the Mapper interface. Under mappers, a folder called mappers is pressed under the Resources path to create the mapping configuration file.
Requirements:
-
The namespace must be consistent with the fully qualified name of the corresponding Mapper interface
-
The add, delete, change, and query methods in the Mapper interface correspond to the INSERT, DELETE, Update, and SELECT labels in the mapping configuration file
- The tag ID corresponds to the method name
- The parameterType attribute of the tag specifies the parameterType of the method
- The resultType attribute of the tag (available only to the SELECT tag) corresponds to the return value type of the method
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! There are two ways to get user input: 1. ${} --> = ${} --> = ${} -->
<mapper namespace="Mapper.EmployeeMapper">
<insert id="insertEmployee">
insert into t_emp (emp_name,emp_salary) values (#{empName},#{empSalary})
</insert>
<delete id="deleteEmployee">
delete from t_emp where emp_id=#{empId}
</delete>
<update id="updateEmployee">
update t_emp set emp_name=#{param2} where emp_id=#{param1}
</update>
<select id="selectEmployee" resultType="pojo.Employee">
select emp_id empId, emp_name empName,emp_salary empSalary from t_emp where emp_id=#{empId}
</select>
</mapper>
Copy the code
Supplementary data input and output
7.1. The input
7.1.1 Method of obtaining input information
#{} (recommended)
Mybatis converts #{} from SQL statements in configuration files to “?” Placeholder that is sent to the database for execution. Mapping file configuration:
<delete id="deleteEmployee">
delete from t_emp where emp_id=#{empId}
</delete>
Copy the code
Delete from t_emp where emp_id=?
${} (not recommended, SQL injection problem)
Mybatis will spell strings according to ${} in the future while running
7.2. The output
Only the SELECT tag has output, and we currently specify the type of output using the resultType attribute
<select id="selectEmployee" resultType="pojo.Employee">
select emp_id empId, emp_name empName,emp_salary empSalary from t_emp where emp_id=#{empId}
</select>
Copy the code
8. Test the program
To get the proxy object of the Mapper interface, and call the method to execute the SQL statement, and then use the Spring framework.
import Mapper.EmployeeMapper;
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.After;
import org.junit.Before;
import pojo.Employee;
import java.io.InputStream;
public class Test {
private EmployeeMapper employeeMapper;
private InputStream is;
private SqlSession sqlSession;
@Before
public void init(a) throws Exception{
// Target: Get the proxy object for the EmployeeMapper interface and use it to call the selectEmployee(1) method and return the Employee object
//1. Convert the global configuration file into a byte input stream
is = Resources.getResourceAsStream("mybatis-config.xml");
//2. Create the SqlSessionFactoryBuilder object
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3. Create the SqlSessionFactory object using the Builder pattern
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//4. Create a SqlSession object using factory mode
sqlSession = sqlSessionFactory.openSession();
//5. Use the dynamic proxy mode to create a proxy object for the EmployeeMapper interface
employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
}
@org.junit.Test
public void testInsertEmployee(a){
Employee employee = new Employee(null."Amy".500d);
// Calls the insertEmployee() method of the employeeMapper object
employeeMapper.insertEmployee(employee);
}
@After
public void after(a) throws Exception{
// Commit transaction!!
sqlSession.commit();
//7. Close resources
is.close();
sqlSession.close();
}
@org.junit.Test
public void testDeleteEmployee(a){
employeeMapper.deleteEmployee(2);
}
@org.junit.Test
public void testUpdateEmployee(a){
employeeMapper.updateEmployee(3."Salar");
}
@org.junit.Test
public void testSelectEmployee(a){
Employee employee=employeeMapper.selectEmployee(1); System.out.println(employee); }}Copy the code
These are the steps of mybatis first introductory case