七、Mybatis整合spring之手动实现dao层

环境搭建

1.新建工程,添加jar包
由于后面的测试我是使用Junit来完成的,因此我没有创建web工程,而是创建的java工程,创建完工程后,导入相关jar包,我这里给出下载链接,提取码:80xh
在这里插入图片描述
将上图框中的文件夹内的jar导入你的工程,一共31个jar包。
在这里插入图片描述
2.创建javabean及对应操作的数据库表

package blog.csdn.net.mchenys.pojo;

import java.util.Date;

public class User { 
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    //getter and setter...
}
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

表中随意添加一些数据
在这里插入图片描述
3.添加相关配置文件
eclipse中切换为Project Explore视图,在工程根目录下新建一个叫config的Source Folder文件夹,注意一点是new Source Folder 而不是 new Folder,否则后面你会发现无法加载到配置文件,这里顺带说一下什么是 Source Folder?

Source Folder文件夹是一种特别的文件夹,它是用来存放java源代码的文件夹,当然也包括一些package文件夹,还可以用来存放其他文件,例如配置文件,其实工程下的src目录就是默认的Source Folder。
如果是web项目,项目构建后,source folder里面的java文件会自动编译成class文件到相应的WEB-INF/classes文件夹中,其他文件也会被移到WEB-INF/classes文件夹中。

我这里为什么不把配置文件直接放到src目录下是因为不好维护,我单独放到一个Source Folder将它们和java代码分开管理,一目了然,ok,这里我一共需要添加这么几个配置文件:
在这里插入图片描述
一个个结束吧,log4j.properties就是日志文件的配置,这个前面的文章也介绍过,这里直接拿来用,有了它,控制台就可以输出Mybatis相关的log

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

User.xml,Mybatis的映射文件,用来定义sql语句以及javabean和数据库表字段的对应关系用的,前面文章也介绍过,这里不多说,直接看内容:

<?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">

<!-- namespace:命名空间,可任意起名,代码中会通过该名称空间来调用具体的sql语句 -->
<mapper namespace="test">
	<!-- 
		id:语句的唯一标识
		parameterType:指定传入参数类型,可以是包装类型的全类名,也可以直接写基本类型
		resultType:返回结果集的类型,可以是基本类型,也可以是引用类型
		#{}:占位符,如果传入的如果是基本类型(string,long,double,int,boolean,float等),那么#{}中的变量名称可以随意写
	 -->
	<select id="findUserById" parameterType="java.lang.Integer" resultType="blog.csdn.net.mchenys.pojo.User">
		select * from user where id = #{id}
	</select>
</mapper>

SqlMapConfig.xml,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">
<configuration>
	
	<!-- 配置映射文件 -->
	<mappers>	
		<mapper resource="User.xml"/>
	</mappers>
</configuration>

你可能会好奇,之前在Mybatis配置文件中都会有数据库连接池的配置,怎么现在没有了,其实还是有的,只是当集成了Spring的时候,就可以交给Spring的配置文件去配置,ok,那就到Spring的配置文件了ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	
	<!-- 数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>
	
	<!-- 整合Sql会话工厂归spring管理 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定mybatis核心配置文件 -->
		<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
		<!-- 指定会话工厂使用的数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
</beans>

注意在Spring配置文件中引入其他配置文件时,必须要加上前缀classpath,在java代码中则可以不用加,classpath对应的是工程根目录下的Source Folder目录,刚好我们的配置文件就是放在根目录下的config Source Folder中,所以Spring能够找到它们。

最后一个db.properties,在Spring配置文件中设置数据库连接池时有用到,使用前需要通过context:property-placeholder标签导入,db.properties内配置的就是数据库连接池需要用到的参数:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

编写代码

1.添加dao层接口和实现类
在src目录下创建dao层的包
在这里插入图片描述
添加如下接口和实现类

package blog.csdn.net.mchenys.dao;
import blog.csdn.net.mchenys.pojo.User;

public interface UserDao {
	public User findUserById(Integer id);
}

package blog.csdn.net.mchenys.dao;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import blog.csdn.net.mchenys.pojo.User;

/**
 * dao层手动实现,需要继承SqlSessionDaoSupport类
 * @author mChenys
 *
 */
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

	@Override
	public User findUserById(Integer id) {
		//调用父类的的方法获取session
		SqlSession openSession = this.getSqlSession();
		
		//调用sql语句需要用到映射文件中的namespace+sql语句的id
		User user = openSession.selectOne("test.findUserById", id);
		
		//整合后会话归spring管理,所以不需要手动关闭.
		//openSession.close();
		return user;
	}
}

2.在Spring配置中注入dao实现类

编辑ApplicationContext.xml文件,添加下面内容到beans标签内。

	<!-- 
		配置原生Dao实现  	
		注意:class必须指定Dao实现类的全路径名称
	-->
	<bean id="userDao" class="blog.csdn.net.mchenys.dao.UserDaoImpl">
		<!-- 注入sqlSessionFactory -->
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	

3.添加测试类
在工程根目录下新建一个叫test的Source Folder,然后在其内新建测试包和测试类
在这里插入图片描述
测试类代码如下:

package blog.csdn.net.mchenys.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import blog.csdn.net.mchenys.dao.UserDao;
import blog.csdn.net.mchenys.pojo.User;

public class UserDaoTest {

	private ApplicationContext applicationContext;

	@Before
	public void setUp() throws Exception {
		//代码中classpath可加可不加,xml中必须要加
		applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
	}

	@Test
	public void testFindUserById() throws Exception {
		UserDao dao = (UserDao) applicationContext.getBean("userDao");
		User user = dao.findUserById(1);
		System.out.println(user);

	}
}

执行Junit测试结果:
在这里插入图片描述
可以看到绿条通过,同时控制台能看到这条sql记录那就说明整合Spring成功了。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值