使用java反射机制与mybatis框架搭建DAO层,实现数据的传输,简化了实现类中每次写得到和关闭sqlSession,交给工具类来处理。

JDBC工具类:

package com.school.api.conf.jdbc;

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;

public class JDBCUtil {
	public JDBCUtil() {}
	private static SqlSessionFactory sqlSessionFactory = null;
	private static InputStream in = null;
	static {
		try {
			in = Resources.getResourceAsStream("mybatis.xml");
			sqlSessionFactory =new SqlSessionFactoryBuilder().build(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到sqlSession
	 * @return
	 */
	public static SqlSession getSqlSession() {
		SqlSession sqlSession = null;
		try {
			sqlSession=sqlSessionFactory.openSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlSession;
	}
	
	/**
	 *  关闭SqlSession
	 * @param sqlSession
	 */
	public static void closeSqlSession(SqlSession sqlSession){
		if(sqlSession != null)
			sqlSession.close();
	}
	public static void main(String[] args) {
		System.out.println(getSqlSession());
	}
}

mybatis.xml配置文件:

<?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>
<properties resource="jdbc.properties"></properties>
	<settings>  
		<setting name="mapUnderscoreToCamelCase" value="true" />
		<setting name="logImpl" value="LOG4J"></setting>  
    </settings>
    <typeAliases>
    	<package name="com.school.api.pojo"/>
    </typeAliases>
     <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
    <mappers>
    	<mapper resource="com/school/api/dao/mapping/grade-mapping.xml"/>
    </mappers>
</configuration>

BaseSqlMapperDao工具类:

package com.school.api.conf.sqlmapper;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.school.api.conf.jdbc.JDBCUtil;
/**
 * 
 * @author zuiweng clq_zuiweng@163.com
 * 2019年9月21日
 */
@SuppressWarnings("unchecked")
public class BaseSqlMapperDao {
	Logger logger  = Logger.getLogger(BaseSqlMapperDao.class);
	SqlSession sqlSession = null;
	
	/**
	 * 
	 * @param clazz  该参数为对应xxxDao.class
	 * @param t  参数为对象类型,实体类
	 * @param methodName 要执行的方法名称
	 * @return
	 * @throws Exception
	 */
	public  <T> int saveFlushDelCount(Class<?> clazz,T t,String methodName) throws Exception{
		int result = 0;
		String[] before =new String[] {"save","add","flush","update","delete","del","count"};
		List<String> list =Arrays.asList(before);
		boolean flag = false;
		for(String str : list) {
			if(methodName != null && !"".equals(methodName)) {
				if(methodName.contains(str)) {
					flag = true;
					break;
				}
			}else {
				logger.error("methodName方法名不能为空");
				throw new Exception("methodName方法名不能为空");
			}
		}
		
		if(flag) {
			sqlSession = JDBCUtil.getSqlSession();
			T mapperDao = (T) sqlSession.getMapper(clazz);
			Method method = clazz.getMethod(methodName,new Class[] {Object.class});
			result = (Integer) method.invoke(mapperDao, new Object[] {t});
			logger.debug("DAO类型:---------"+clazz.getName());
			logger.debug("对象类型:---------"+t);
			logger.debug("执行的方法名是:---------"+methodName);
			sqlSession.commit();
			JDBCUtil.closeSqlSession(sqlSession);
		}else {
			String errorStr = "save,add,flush,update,delete,del,count";
			logger.error("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
			throw new Exception("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
		}
		return result;
	}
	
	
	/**
	 * 
	 * @param clazz 该参数为对应xxxDao.class
	 * @param map 参数为map泛型集合
	 * @param methodName  要执行的方法名称
	 * @return
	 * @throws Exception
	 */
	public  <T> int saveFlushDelCount(Class<?> clazz,Map<String,Object> map,String methodName) throws Exception{
		int result = 0;
		String[] before =new String[] {"save","add","flush","update","delete","del","count"};
		List<String> list =Arrays.asList(before);
		boolean flag = false;
		for(String str : list) {
			if(methodName != null && !"".equals(methodName)) {
				if(methodName.contains(str)) {
					flag = true;
					break;
				}
			}else {
				System.err.println("methodName方法名不能为空");
				logger.error("methodName方法名不能为空");
				
				throw new Exception("methodName方法名不能为空");
			}
		}
		
		if(flag) {
			sqlSession = JDBCUtil.getSqlSession();
			T mapperDao = (T) sqlSession.getMapper(clazz);
			Method method = clazz.getMethod(methodName,new Class[] {Map.class});
			result = (Integer) method.invoke(mapperDao, new Object[] {map});
			logger.debug("DAO类型:---------"+clazz.getName());
			logger.debug("map集合为:---------"+map);
			logger.debug("执行的方法名是:---------"+methodName);
			sqlSession.commit();
			JDBCUtil.closeSqlSession(sqlSession);
		}else {
			String errorStr = "save,add,flush,update,delete,del,count";
			logger.error("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
			new Exception("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
		}
		return result;
	}
	
	/**
	 * 
	 * @param clazz 该参数为对应xxxDao.class
	 * @param id 唯一id
	 * @param methodName 方法名
	 * @return 当执行的方法为查询某条数据时返回对象(需强转),当执行的方法为删除时则返回影响的行数
	 * @throws Exception
	 */
	public <T> Object queryOrDelOne(Class<?> clazz,Integer id,String methodName) throws Exception {
		Object result = 0;
		String[] before =new String[] {"query","get","delete","del"};
		List<String> list =Arrays.asList(before);
		boolean flag = false;
		for(String str : list) {
			if(methodName != null && !"".equals(methodName)) {
				if(methodName.contains(str)) {
					flag = true;
					break;
				}
			}else {
				logger.error("methodName方法名不能为空");
				throw new Exception("methodName方法名不能为空");
			}
		}
		

		if(flag) {
			sqlSession = JDBCUtil.getSqlSession();
			T mapperDao = (T) sqlSession.getMapper(clazz);
			Method method = clazz.getMethod(methodName,new Class[] {int.class});
			result = method.invoke(mapperDao, new Object[] {id});
			logger.debug("DAO类型:---------"+clazz.getName());
			logger.debug("参数id为:---------"+id);
			logger.debug("执行的方法名是:---------"+methodName);
			if(methodName.contains("del") || methodName.contains("delete")) {//查询不需要提交事务
				sqlSession.commit();
			}
			JDBCUtil.closeSqlSession(sqlSession);
		}else {
			String errorStr = "query,get,delete,del";
			logger.error("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
			throw new Exception("该方法应为返回值为int类型,并且方法名中包含:"+errorStr);
		}
		return result;
	}
	
	/**
	 * 集合查询
	 * @param clazz 该参数为对应xxxDao.class
	 * @param t参数对象类型
	 * @param methodName
	 * @return 
	 * @throws Exception
	 */
	
	public <T> List<T> queryList(Class<?> clazz,T t,String methodName) throws Exception{
		List<T> resT = null;
		sqlSession = JDBCUtil.getSqlSession();
		T mapperDao = (T) sqlSession.getMapper(clazz);
		Method method = clazz.getMethod(methodName,new Class[] {Object.class});
		resT =(List<T>) method.invoke(mapperDao, new Object[] {t});
		logger.debug("DAO类型:---------"+clazz.getName());
		logger.debug("参数类型为:---------"+t);
		logger.debug("执行的方法名是:---------"+methodName);
		JDBCUtil.closeSqlSession(sqlSession);
		return resT;
	}
	
	public <T> List<T> queryList(Class<?> clazz,Map<String,Object> map,String methodName) throws Exception{
		List<T> resT = null;
		sqlSession = JDBCUtil.getSqlSession();
		T mapperDao = (T) sqlSession.getMapper(clazz);
		Method method = clazz.getMethod(methodName,new Class[] {Map.class});
		resT =(List<T>) method.invoke(mapperDao, new Object[] {map});
		logger.debug("DAO类型:---------"+clazz.getName());
		logger.debug("参数类型为:---------"+map);
		logger.debug("执行的方法名是:---------"+methodName);
		JDBCUtil.closeSqlSession(sqlSession);
		return resT;
	}
	
}

grade-mapping.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.school.api.dao.GradeDao">
	<insert id="save" parameterType="com.school.api.pojo.Grade" useGeneratedKeys="true"
		keyProperty="id">
		insert into scl_grade
		(
		title,
		school_id
		)values(
		#{title},
		#{school_id}
		)
	</insert>
	
	
	
	<update id="flush" parameterType="com.school.api.pojo.Grade">
		update scl_grade
		<trim prefix="set" suffixOverrides="," suffix="where id=#{id}">
				<if test="title != null and title != '' ">title=#{title},</if>
				<if test="school_id != null and school_id != '' ">school_id=#{school_id},</if>
		</trim>
	</update>
	
	<delete id="deleteOne">
		delete from scl_grade where id=#{id}
	</delete>
	
	<select id="queryOne" resultMap="resClass">
		select * from scl_grade where id=#{id}
	</select>
	
	<select id="queryList" resultMap="resClass">
		select * from scl_grade 
		<where>
			<if test="school_id != null and school_id != '' ">school_id=#{school_id}</if>
		</where>
	</select>
	
	<select id="count" parameterType="com.school.api.pojo.Grade" resultType="java.lang.Integer">
		select COUNT(*) from scl_grade 
		<where>
			<if test="school_id != null and school_id != '' ">school_id=#{school_id}</if>
		</where>
	</select>
	
	

	<resultMap type="com.school.api.pojo.Grade" id="resClass">
		<result column="id" property="id"/>
		<result column="school_id" property="school_id"/>
		<result column="title" property="title"/>
	</resultMap>

</mapper>

最终在web层调用成功查询,插入等操作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值