Mybatis作为一个优秀的ORM框架,是javaee开发者必学的知识之一,博主主要是为了自学,记录在尚硅谷学习mybatis的点滴,本文仅供学习交流。
初识Mybatis
引用官方的话是:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
Mybatis官网:Mybatis
Mybatis github地址:Mybatis源码
Hello World开发
- 数据库表准备
创建数据库
create database `test` character set utf8 collate utf8_general_ci;
创建数据表
create table employee(
id int(11) primary key auto_increment,
last_name varchar(50),
email varchar(50),
gender char(1)
);
添加测试数据:
insert into employee values(1,"tom","tom@qq.com",'1');
- 创建maven工程
- 添加maven依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 添加mybatis支持 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 添加log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- jdbc驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
添加log4j配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" 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="%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c Method: %l ]%n%p:%m%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>
参考mybatis官方手册,需要从 XML 中构建 SqlSessionFactory,mybatis-config.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>
<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://10.166.152.12:3306/test"/>
<property name="username" value="xxx"/>
<property name="password" value="XXX"/>
</dataSource>
</environment>
</environments>
<!---->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
创建与表相对应的bean
package com.xcl.mybatis.beans;
/**
* @author xcl
* @version 1.0
* @date 2019/3/21 10:05
*/
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
}
创建测试类:
package com.xcl.mybatis;
import com.xcl.mybatis.beans.Employee;
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 java.io.InputStream;
/**
* @version 1.0
* @author xcl
* @date 2019/3/21 11:09
*/
public class TestMybatis {
@Test
public void testSqlSessionFactory() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
System.out.println(sqlSessionFactory);
SqlSession session = sqlSessionFactory.openSession();
System.out.println(session);
try {
Employee employee = (Employee) session.selectOne("org.mybatis.example.EmployeeMapper.selectEmployee", 1);
System.out.println(employee);
} finally {
session.close();
}
}
}
上述测试类中引用SqlSession,需要通过xml定义,EmployeeMapper.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">
<mapper namespace="org.mybatis.example.EmployeeMapper">
<select id="selectEmployee" resultType="com.xcl.mybatis.beans.Employee">
select * from employee where id = #{id}
</select>
</mapper>
执行结果为:
我们发现lastname为null,这样是不对的,select最好不用*,我们修改为:
<?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="org.mybatis.example.EmployeeMapper">
<select id="selectEmployee" resultType="com.xcl.mybatis.beans.Employee">
select id,last_name lastname,email,gender from employee where id = #{id}
</select>
</mapper>
结果正常:
- github 地址
https://github.com/chuanleixu/Mybatis_Tutorials