Mybatis接口式编程(推荐)
SqlSession代表和数据库的一次会话,用完必须关闭
SqlSession和connection一样都是非线程安全,每次使用都应该去获取新的对象
mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象
(将接口和XML进行绑定)
EmployeeMapper empMapper=sqlSession.getMapper(EmployeeMapper.class)
两个重要的配置文件:
mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息
sql映射文件:保存了每一个sql语句的映射信息,就是通过这个配置文件将sql抽取出来
和之前方式不同的一点就是我们需要新建一个接口类,然后将EmployeeMapper.xml和接口连接,就当做xml里面的映射sql语句为接口的实现。(EmployeeMapper文件就是从数据库表中查出数据封装为对象,正好对应接口的功能)
所以命名空间要指定为接口的全类名,就知道xml文件和接口进行绑定
<mapper namespace="com.yorkmass.mybatis.dao.EmployeeMapper">
将EmployeeMapper.xml里面的select标签id和接口里面的方法进行绑定
<select id="getEmpById" resultType="com.yorkmass.mybatis.bean.Employee">
select id,last_name lastName,email,gender from tbl_employee where id = #{id}
</select>
然后主程序通过获取接口的实现类对象,为接口自动的创建一个代理对象,代理对象去执行增删改查方法
示例代码:
准备:新建lib文件夹导入所需要的jar包,步骤和上条博客一样https://blog.csdn.net/qq_36949176/article/details/86597582
代码结构如上
Employee类
package com.yorkmass.mybatis.bean;
public class Employee {
private Integer id;
private String lastName;
private String email;
private String 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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
}
}
EmployeeMapper接口
package com.yorkmass.mybatis.dao;
import com.yorkmass.mybatis.bean.Employee;
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
MybatisTest类
package com.yorkmass.mybatis.test;
import java.io.IOException;
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 com.yorkmass.mybatis.bean.Employee;
import com.yorkmass.mybatis.dao.EmployeeMapper;
public class MyBatisTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
* 有数据源一些运行环境信息
* 2、sql映射文件;配置了每一个sql,以及sql的封装规则等。
* 3、将sql映射文件注册在全局配置文件中
* 4、写代码:
* 1)、根据全局配置文件得到sqlSessionFatory;
* 2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
* 一个sqlSession就是代表和数据库的一次会话,用完关闭
* 3)、使用sql的唯一标识来告诉MyBatis执行哪个sql,sql都是保存在映射文件中的
* @throws IOException
*/
// @Test
// public void test() throws IOException {
// String resource = "mybatis-config.xml";
// InputStream inputStream = Resources.getResourceAsStream(resource);
// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// //获取sqlSession实例,能直接执行已经映射的sql语句
// //sql的唯一标识:statement Unique identifier matching the statement to use.
// //执行sql要用的参数:parameter A parameter object to pass to the statement.
// SqlSession openSession = sqlSessionFactory.openSession();
// try {
// Employee employee=openSession.selectOne("com.yorkmass.mybatis.EmployeeMapper.selectEmp", 1);
// System.out.println(employee);
// } finally {
// openSession.close();
// }
// }
@Test
public void test01() throws IOException{
//1、获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory= getSqlSessionFactory();
//2、获取sqlSession对象
SqlSession openSession =sqlSessionFactory.openSession();
try{
//3、获取接口的实现类对象
//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
Employee employee=mapper.getEmpById(2);
System.out.println(mapper.getClass());
System.out.println(employee);
}finally {
openSession.close();
}
}
}
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="com.yorkmass.mybatis.dao.EmployeeMapper">
<!--
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
public Employee getEmpById(Integer id);
-->
<select id="getEmpById" resultType="com.yorkmass.mybatis.bean.Employee">
select id,last_name lastName,email,gender from tbl_employee where id = #{id}
</select>
</mapper>
mybatis-config.xml配置文件(主要连接数据库用,和注册写好的sql映射文件)
<?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://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="yywy2018"/>
</dataSource>
</environment>
</environments>
<!-- 将我们写好的sql映射文件一定要注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
log4j.xml日志配置文件(可去官网下载)
<?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>
运行结果:
DEBUG 01-23 17:36:00,627 ==> Preparing: select id,last_name lastName,email,gender from tbl_employee where id = ? (BaseJdbcLogger.java:145)
DEBUG 01-23 17:36:00,652 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 01-23 17:36:00,665 <== Total: 1 (BaseJdbcLogger.java:145)
class com.sun.proxy.$Proxy4
Employee [id=2, lastName=hh, email=1196531291@qq.com, gender=0]