SpringMVC关于MyBatis通用公共Dao的实现

现在越来越多的开发者使用MyBatis作为ORM的框架,它开发迅速,上手容易,开源代码多。但是在进行数据库操作的时候的独自生成的DaoMaper业务太多,在相互调用的业务之间,容易产生这样那样的事务问题。因此本人一直想寻找一个类似Hibernate一样的通用数据库管理Dao,采用Spring注入的方式即可。现在已创建项目的方式和大家一起分享。

一、IDEA创建web项目

(1)、File——New——Project,选择Java——Web Application

(2)、添加Maven依赖,右键项目——Add Framework Support

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.chentian610</groupId>
    <artifactId>GeneralDao</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>4.2.2.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
    </dependencies>
</project>
其中dependencyManagement中的spring-framework-bom是spring整理的版本控制,只需要在这里配置好spring的版本,后面的spring依赖都无需指定版本了,方便统一版本升级。

(3)、创建springContent.xml并在web.xml中指定

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
(4)、创建数据库连接配置文件jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
 
jdbc.databaseURL=jdbc:mysql://127.0.0.1:3306/chentian610?useUnicode=true&autoReconnect=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=a
(5)、在springContent.xml中指定jdbc配置

<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.databaseURL}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>
(6)、集成MyBatis组件sqlSessionFactory

	<!--以下是将Mybatis注入到通用Dao中 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatisframework.xml" />
		<property name="mapperLocations"
			value="classpath*:com/chentian610/**/config/*.xml" />
	</bean>
	<!--ibatis升级到mybatis后,sqlMapClient也升级到 SqlSessionTemplate chentian610 -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
(7)、配置数据库事务

<!-- JDBC事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

  	<!-- 配置事务特性 -->
  	<tx:advice id="txAdvice" transaction-manager="transactionManager">
   	 <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" isolation="REPEATABLE_READ" rollback-for="RuntimeException"/>
    </tx:attributes>
  </tx:advice> 

	<aop:config>
	       <aop:pointcut id="txPointcut" expression="execution(* com.chentian610.*.service.*.*(..))" />
	       <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
	</aop:config>
(8)、’编写公共GeneralDao

	@Autowired
	public void setSqlSession(SqlSessionTemplate sqlMapClient) {
		this.sqlSession = sqlMapClient;
		_logger.info("Mybatis数据库连接对象注入GeneralDAO完成");
	}

	public <T> T queryObject(String sqlId, Object param) {
		try {
			return sqlSession.selectOne(sqlId, param);
		} catch (Exception e) {
			throw handException(e);
		}
	}

	public <T> List<T> queryForList(String sqlId, Object param) {
		List<T> list = null;
		if (ActionUtil.isPage_app()) {//手机APP分页
			List<T> list2 = sqlSession.selectList(sqlId,param,new RowBounds(ActionUtil.getStart(),ActionUtil.getLimit()));
			if (ListUtil.isEmpty(list2)) return new ArrayList<T>();
			if (ActionUtil.isDirection_pre() && (ActionUtil.getStart()==0)){
				list = new ArrayList<T>();
				for (int i=list2.size()-1;i>-1;i--) list.add(list2.get(i));
			} else list = list2;
		}  else if (ActionUtil.isPage_web()) //Web端分页
			 list = sqlSession.selectList(sqlId, param,new RowBounds(ActionUtil.getStart(),ActionUtil.getLimit()));
		else list = sqlSession.selectList(sqlId, param);//不分页
		Integer total = sqlSession.selectOne("systemMap.getListCount");
		ActionUtil.setTotal(total);
		return list;
	}
(9)、在业务代码中引用GeneralDao
package com.chentian610.test.service.impl;

import com.chentian610.framework.GeneralDAO;
import com.chentian610.test.service.TestService;
import com.chentian610.test.vo.TestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value="TestServiceImpl")
public class TestServiceImpl implements TestService {
	@Autowired
	private GeneralDAO dao;

	public void addTest(TestVO vo) {
		Integer id = dao.insertObjectReturnID("testMap.insertTest",vo);
		vo.setId(id);
	}

	public void updateTest(TestVO vo) {
		dao.updateObject("testMap.updateTest",vo);
	}

	public void deleteTest(TestVO vo) {
		dao.deleteObject("testMap.deleteTestById",vo.getId());
	}

	public List<TestVO> getTestList(TestVO vo) {
		return dao.queryForList("testMap.getTestList",vo);
	}
}

(10)、controller层注入业务层

package com.chentian610.test.controller;

import com.chentian610.test.service.TestService;
import com.chentian610.test.vo.TestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="testAction")
public class TestController {
	@Autowired
	private TestService testService;

	/**
	 * 添加
	 * @param vo
	 */
	@RequestMapping(value="/addTest")
	public Object addTest(TestVO vo){
		testService.addTest(vo);
		return "添加成功";
	}

	/**
	 * 修改
	 * @param vo
	 */
	@RequestMapping(value="/updateTest")
	public Object updateTest(TestVO vo){
		testService.updateTest(vo);
		return "修改成功";
	}


	/**
	 * 删除
	 * @param vo
	 */
	@RequestMapping(value="/deleteTest")
	public Object deleteTest(TestVO vo){
		testService.deleteTest(vo);
		return "删除成功";
	}

	/**
	 * 查询
	 * @param vo
	 */
	@RequestMapping(value="/getTestList")
	public Object getTestList(TestVO vo){
		return testService.getTestList(vo);
	}
	
}
(11)、代码编写完成,启动项目,输入http://localhost:8080/{发布的项目名称}/testAction/getTestList

最后:源码git地址 OR CSDN下载地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值