MyBatis笔记:接口式编程

Mybatis接口式编程(推荐)

和之前方式不同的一点就是我们需要新建一个接口类,然后将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执行哪个sqlsql都是保存在映射文件中的
	 * @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]

 

赞赏解锁

赞赏VIP特权
赞赏成功后,解锁全站内容!

XML相关文章

本文详细介绍了 torch.manual_seed(seed) 及其用法
本文主要讲述了文件读取的绝对路径和相对路径;导包...
L1研发工程师-编程题、选择题
OpenCV 是一个的跨平台计算机视觉库,它轻量且高效—...
1 集成模型简介集成学习模型使用一系列弱学习器(也...
散点图是可视化的一种常见形式