Spring与Mybatis整合

一.创建数据库表

-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(20) NOT NULL,
  `email` varchar(20) DEFAULT NULL,
  `date` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES ('1', 'aaa', 'heimao@163.com', '2017-12-04', '18');
INSERT INTO `students` VALUES ('2', 'ccc', 'heimao@163.com', '2017-11-30', '15');
INSERT INTO `students` VALUES ('3', 'mike', 'mike@sina.com', '2017-12-06', '20');
INSERT INTO `students` VALUES ('4', 'zhangsan', 'zhang@qq.com', '2017-12-11', '22');
INSERT INTO `students` VALUES ('5', '刘芳', 'liufang@263.com', '2017-12-10', '19');
INSERT INTO `students` VALUES ('6', '批量', '125@.com', '2017-8-7', '18');
INSERT INTO `students` VALUES ('7', '屠浩层', ' thc@163.com', '2017-12-05', '22');
INSERT INTO `students` VALUES ('8', '樱桃小丸子', 'xiaowanzi@163.com', '2017-12-04', '36');
INSERT INTO `students` VALUES ('9', '熊二', 'xionger@qq.com', '2017-12-12', '28');
INSERT INTO `students` VALUES ('10', '翠花', 'cuihua@qq.com', '2017-12-03', '23');
INSERT INTO `students` VALUES ('11', '菲菲', 'fei@163.com', '2017-12-03', '21');
INSERT INTO `students` VALUES ('12', '批量', 'la@qq.com', '2017-11-28', '18');
INSERT INTO `students` VALUES ('13', '黑猫警长', 'heimao@163.com', '2017-12-05', '25');
INSERT INTO `students` VALUES ('14', '黑侠', '222@.com', '2017-8-7', '25');
INSERT INTO `students` VALUES ('17', '迭峰', 'df@qq.com', '2018-01-20', '18');
INSERT INTO `students` VALUES ('19', '蜂肥肥', 'mf@qq.com', '2018-01-20', '18');
INSERT INTO `students` VALUES ('20', '牛发', 'nn@qq.com', '2018-01-18', '20');
INSERT INTO `students` VALUES ('31', '强子', 'qiang@163.com', '2018-01-19', '5');

二.添加依赖包


三.新建POJO实体层

 

import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class Student {
	private int id;
	private String user;
	private String email;
	private Date date;
	private int age;

 四.底层数据接口

 

import java.util.List;

import com.hlx.entity.Student;

/**
 * Dao接口
 * 
 * @author Administrator
 * 
 */
public interface StudentDao {
	int add(Student student); // 添加

	int del(int id);// 删除

	int update(Student student);// 更新

	List<Student> all();// 查询所有的数据

	Student findById(int id); // 根据ID查询数据
}
五.Mybatis配置文件

<?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.hlx.dao.StudentDao">

<!-- 查询所有的数据 -->
<select id="all" resultType="Student">
 select * from students
</select>


<!-- 根据ID查询数据 -->
<select id="findById" resultType="Student" parameterType="int">
 select * from students where id=#{id}
</select>


<!-- 添加 -->
<insert id="add" parameterType="Student" useGeneratedKeys="true" keyColumn="id">
  insert into students(user,email,date,age) values(#{user},#{email},#{date},#{age})
</insert>


<!-- 更新 -->
<update id="update" parameterType="Student" >
  update students set user=#{user},email=#{email},date=#{date},age=#{age} where id=#{id}
</update>

<!-- 删除 -->
<update id="del" parameterType="int" >
  delete from students where id=#{id}
</update>

</mapper>

六.业务层接口

public interface StudentBiz {
	int save(Student student); // 添加

	int delete(int id);// 删除

	int update(Student student);// 更新

	List<Student> alls();// 查询所有的数据

	Student findById(int id); // 根据ID查询数据
}


实现业务层接口

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hlx.biz.StudentBiz;
import com.hlx.dao.StudentDao;
import com.hlx.entity.Student;

@Service
public class StudentBizImpl implements StudentBiz {
	
	@Autowired
	private StudentDao studentDao;

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public int save(Student student) {
		// TODO Auto-generated method stub
		return studentDao.add(student);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public int delete(int id) {
		// TODO Auto-generated method stub
		return studentDao.del(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public int update(Student student) {
		// TODO Auto-generated method stub
		return studentDao.update(student);
	}

	@Override
	@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
	public List<Student> alls() {
		// TODO Auto-generated method stub
		return studentDao.all();
	}

	@Override
	@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
	public Student findById(int id) {
		// TODO Auto-generated method stub
		return studentDao.findById(id);
	}

}


七.applicationContext.xml文件

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

	<!-- 1.加载jdbc.properties文件 -->
	<context:property-placeholder location="classpath*:jdbc.properties" />

	<!--2 配置C3P0数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<!-- driver -->
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<!-- url -->
		<property name="jdbcUrl" value="${jdbc.url}" />
		<!-- username -->
		<property name="user" value="${jdbc.username}" />
		<!-- pwd -->
		<property name="password" value="${jdbc.password}" />
		<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
		<property name="acquireIncrement" value="5" />
		<!-- 初始连接池大小 -->
		<property name="initialPoolSize" value="10" />
		<!-- 连接池中连接最小个数 -->
		<property name="minPoolSize" value="5" />
		<!-- 连接池中连接最大个数 -->
		<property name="maxPoolSize" value="20" />
	</bean>

	<!--3 mybatis 会话工厂bean sqlSessionFactoryBean -->
	<bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 实体类别名 -->
		<property name="typeAliasesPackage" value="com.hlx.entity" />
		<!-- mapper sql映射文件路径 -->
		<property name="mapperLocations" value="classpath*:com/hlx/mapper/*Mapper.xml" />
	</bean>

	<!--4 自动扫描对象关系映射 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去; 不可以用ref哦!! -->
		<property name="sqlSessionFactoryBeanName" value="sessionFactoryBean" />
		<!-- 指定要自动扫描接口的基础包,实现接口 -->
		<property name="basePackage" value="com.hlx.dao" />
	</bean>


	<!--5 声明式事务管理 -->
	<!--定义事物管理器,由spring管理事务 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!--支持注解驱动的事务管理,指定事务管理器 -->
	<tx:annotation-driven transaction-manager="transactionManager" />

	<!--6 容器自动扫描IOC组件 -->
	<context:component-scan base-package="com.hlx" />

	<!--7 aspectj支持自动代理实现AOP功能 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>


八,测试类:

 

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hlx.biz.StudentBiz;
import com.hlx.entity.Student;

@RunWith(SpringJUnit4ClassRunner.class) //加载spring-test.jar测试
@ContextConfiguration(locations="classpath*:applicationContext.xml") //加载配置文件
public class TestStudent {
	
	//注入业务层
	@Autowired
	private StudentBiz biz;

	@Test
	public void all(){
		List<Student> list =biz.alls();
		for (Student student : list) {
			System.out.println(student);
		}
	}
}

完毕!


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值