第一部分:Common.xml (mybatis sql执行文件 这里通过java传参形成sql语句)
下面包含各种传参查询和传入sql语句进行查询(注入问题在java中进行处理)
添加和批量添加
批量删除
修改在CommonDao中
第二部分:CommonMapper.java (接口类)
第三部分: CommonDao.java 基于 CommonMapper实现sql语句实现方法调用参数化(具体方法查看 CommonDao类中有注释 )
第四部分: Params.java, ParamCondition.java (参数接受传递类,具体参数查看此类)
第五部分: Mybatis.xml (mybatis与mysql之间的数据连接配置)
第六部分:jdbc.properties (数据源配置)
第七部分:pom.xml (maven包引用配置)
第八部分: CommonDaoTest (测试类)
Common.xml
${value}
${value}
${value}
${value}
insert into ${tables}
${k}
values
#{v}
insert into ${tables}
${k}
values
#{v}
DELETE FROM ${tables} WHERE ${deleteCoulumnName}
#{id}
CommonMapper.java
package com.beijingserver.mapper;
import java.util.List;
import java.util.Map;
import com.beijingserver.pojo.Params;
public interface CommonMapper {
/**
* 执行增删改sql语句
*
* @author zhy
* @param sql sql语句
* @return
*/
public long executeAction(String sql);
/**
* 根据sql语句查询单调数据
*
* @author zhy
* @param sql sql语句
* @return
*/
public Map findOneData(String sql);
/**
* 根据sql语句查询多调数据
*
* @author zhy
* @param sql sql语句
* @return
*/
public List> findManyData(String sql);
/**
* 添加实体数据
*
* @author zhy
* @param params 添加参数类
* @return
*/
public int addEntity(Params params);
/**
* 根据sql语句查询条数
*
* @author zhy
* @param sql sql语句
* @return
*/
public long findCount(String sql);
/**
* 批量添加
*
* @author zhy
* @param params 添加参数
* @return
*/
public int batchAdd(Params params);
/**
* 批量删除
*
* @author zhy
* @param params 参数类
* @return
*/
public int batchDelete(Params params);
/**
* 根据sql语句查询单个值
*
* @author zhy
* @param sql sql语句
* @return
*/
public Object findOneValue(String sql);
}
CommonDao.java
package com.beijingserver.dao;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.beijingserver.mapper.CommonMapper;
import com.beijingserver.pojo.Params;
/**
* 类名称:通用DAO实现层 描述:通用数据处理层 创建人:周化益 创建时间:2015-08-05
*/
@Repository("commonDao")
public class CommonDao {
@Autowired
private CommonMapper commonMapper;
/**
* 增删改SQL操作
*
* @param sql 操作的sql语句
* @return
*/
public long executeAction(String sql) {
return commonMapper.executeAction(sql);
}
/**
* 查询单条语句
*
* @param sql 操作的sql语句
* @return
*/
public Map findOneData(String sql) {
return commonMapper.findOneData(sql);
}
/**
* 查询多条语句
*
* @param sql 操作的sql语句
* @return
*/
public List> findManyData(String sql) {
return commonMapper.findManyData(sql);
}
/**
* 查找数量
*
* @author zhy
* @param sql 查询的sql 语句
* @return
*/
public long findCount(String sql) {
return commonMapper.findCount(sql);
}
/**
* 查询单个
*
* @author zhy
* @param sql 查询的sql 语句
* @return
*/
public Object findOneValue(String sql) {
return commonMapper.findOneValue(sql);
}
/**
* 拼接SQL实现预处理语句
*
* @author zhy
* @param sql 预处理的语句
* @param param 拼接的参数
* @return
*/
protected String sqlAppend(String sql, Map searchParams) {
for (String key : searchParams.keySet()) {
sql = sql.replaceAll(':' + key, '\'' + searchParams.get(key).toString().replaceAll("'", "") + '\'');
}
return sql;
}
/**
* 验证字符串防止sql注入
*
* @author zhy
* @param value 要过滤的值
* @return
*/
protected String validateValue(String value) {
return '\'' + value.replaceAll("'", "") + '\'';
}
/**
* 去掉所有单引号
*
* @author zhy
* @param value 传入的字符串
* @return
*/
protected String deleteSpoit(String value) {
return value.replaceAll("'", "");
}
/**
* 直接拼接参数
*
* @author zhy
* @param searchParams 查询参数
* @return
*/
protected StringBuffer appendWhereSql(Map searchParams) {
StringBuffer sqlBuffer = new StringBuffer("");
if(searchParams != null && searchParams.size() > 0) {
sqlBuffer.append(" where ");
for (String key : searchParams.keySet()) {
sqlBuffer.append(key).append(" = ").append('\'').append(searchParams.get(key).toString().replaceAll("'", "")).append("' or ");
}
int length = sqlBuffer.length();
return sqlBuffer.delete(length - 3, length);
} else {
return sqlBuffer;
}
}
/**
* 得到实体名
*
* @author 周化益
* @param entityName 实体Class
* @return 实体名
*/
private String getTableName(Class extends Object> entityName) {
return entityName.getSimpleName().toUpperCase();
}
/**
* 添加实体
*
* @author 周化益
* @param entityName 实体Class
* @param addData 添加的数据
* @return 主键ID
*/
public long addClass(Class entityName, Map addData) {
Params params = new Params();
params.setTables(getTableName(entityName));
params.setInsertMap(addData);
commonMapper.addEntity(params);
return params.getId();
}
/**
* 批量添加数据
*
* @author zhy
* @param entityName 实体Class
* @param listMap 批量数据集合
* @return
*/
public int batchAdd(Class entityName, List> listMap) {
Params params = new Params();
params.setTables(getTableName(entityName));
params.setInsertMap(listMap.get(0));
params.setBacthInsertMap(listMap);
return commonMapper.batchAdd(params);
}
/**
* 通过条件修改实体
*
* @author 周化益
* @param entityName 实体Class
* @param updataData 修改数据
* @param whereSql 条件语句
* @return 成功或失败
*/
public boolean updateByWhere(Class entityName, Map updateData, String whereSql){
boolean bool = false;
try {
StringBuffer sb = new StringBuffer("update ");
sb.append(getTableName(entityName)).append(" set ");
Iterator it = updateData.keySet().iterator();
StringBuffer updateBuffer = new StringBuffer();
while (it.hasNext()) {
String key = it.next();
if(updateData.get(key) == null) {
updateBuffer.append(key).append('=').append("null").append(',');
} else{
updateBuffer.append(key).append('=').append(':'+key).append(',');
}
}
sb.append(updateBuffer.substring(0, updateBuffer.length() - 1)).append(whereSql);
bool = commonMapper.executeAction(sqlAppend(sb.toString(), updateData)) > 0;
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
public long deleteById(Class entityName, Object id) {
String sql = "delete from " + getTableName(entityName) + " where id = " + id;
return commonMapper.executeAction(sql);
}
/**
* 获取实体字段列表
*
* @author zhy
* @param clazz 实体Class
* @return
*/
public static String getClassColumns(Class> clazz) {
String columns = "";
// 定义实体信息对象
BeanInfo beanInfo;
try {
// 获取实体详细信息
beanInfo = Introspector.getBeanInfo(clazz);
// 获取实体属性描述集合
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
// 获取属性描述
PropertyDescriptor descriptor = propertyDescriptors[i];
// 获取属性名
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
columns += propertyName + ",";
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return columns.substring(0, columns.length() - 1);
}
/**
* 通过实体class获取实体列表数据(无条件)
*
* @author zhy
* @param clazz 实体Class
* @return
*/
public List> getListByBean(Class> clazz) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体数据(无条件)
*
* @author zhy
* @param clazz 实体Class
* @return
*/
public Map getByBean(Class> clazz) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
return commonMapper.findOneData(sql.toString());
}
/**
* 通过实体class获取实体数据
*
* @author zhy
* @param clazz 实体Class
* @param whereSql 查询条件
* @return
*/
public Map getBean(Class> clazz, String whereSql) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//条件
sql.append(' ').append(whereSql);
return commonMapper.findOneData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param clazz 实体Class
* @param whereSql 查询条件
* @return
*/
public List> getListByBean(Class> clazz, String whereSql) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//条件
sql.append(' ').append(whereSql);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param clazz 实体Class
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @return
*/
public List> getListByBean(Class> clazz, String whereSql, int page, int rows) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//条件
sql.append(' ').append(whereSql);
//分页
sql.append(" limit ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param clazz 实体Class
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @param sortColumn 排序字段
* @param sort 排序方式
* @return
*/
public List> getListByBean(Class> clazz, String whereSql, int page, int rows, String sortColumn, String sort) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//条件
sql.append(' ').append(whereSql);
//排序
sql.append(" ORDER BY ").append(sortColumn).append(' ').append(sort);
//分页
sql.append(" LIMIT ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param clazz 实体Class
* @param page 开始页
* @param rows 查询的条数
* @return
*/
public List> getListByBean(Class> clazz, int page, int rows) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//分页
sql.append(" limit ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param clazz 实体Class
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @param sortColumn 排序字段
* @param sort 排序方式
* @return
*/
public List> getListByBean(Class> clazz, int page, int rows, String sortColumn, String sort) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append("SELECT ").append(getClassColumns(clazz)).append(" FROM ").append(getTableName(clazz));
//排序
sql.append(" ORDER BY ").append(sortColumn).append(' ').append(sort);
//分页
sql.append(" LIMIT ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param sqlStr 自己写的SQL语句
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @return
*/
public List> getListByBean(String sqlStr, String whereSql, int page, int rows) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append(sqlStr);
//条件
sql.append(' ').append(whereSql);
//分页
sql.append(" limit ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param sqlStr 自己写的SQL语句
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @param sortColumn 排序字段
* @param sort 排序方式
* @return
*/
public List> getListByBean(String sqlStr, String whereSql, int page, int rows, String sortColumn, String sort) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append(sqlStr);
//条件
sql.append(' ').append(whereSql);
//排序
sql.append(" ORDER BY ").append(sortColumn).append(' ').append(sort);
//分页
sql.append(" LIMIT ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 通过实体class获取实体列表数据
*
* @author zhy
* @param sqlStr 自己写的SQL语句
* @param whereSql 查询条件
* @param page 开始页
* @param rows 查询的条数
* @return
*/
public List> getListByBean(String sqlStr, int page, int rows) {
StringBuffer sql = new StringBuffer();
//查询部分
sql.append(sqlStr);
//分页
sql.append(" limit ").append((page - 1) * rows).append(',').append(rows);
return commonMapper.findManyData(sql.toString());
}
/**
* 批量删除
*
* @author zhy
* @param clazz 实体Class
* @param deleteList 删除的集合
* @param deleteColumnName 批量删除条件字段
* @return
*/
public int batchDelete(Class> clazz, List> deleteList, String deleteColumnName) {
Params params = new Params();
params.setDeleteCoulumnName(deleteColumnName);
params.setDeleteList(deleteList);
params.setTables(getTableName(clazz));
return commonMapper.batchDelete(params);
}
}
Params.java
package com.beijingserver.pojo;
import java.util.List;
import java.util.Map;
public class Params {
/**查询的列*/
private String[] columns;
/**查询的实体*/
private String tables;
/**查询的条件*/
private String whereSql;
/**查询参数拼接*/
private List paramList;
/**起始位置*/
private Integer start;
/**结束位置*/
private Integer end;
/**排序字段*/
private String sortColumn;
/**升序或倒序*/
private String sort;
/**添加参数*/
private Map insertMap;
/**批量添加参数*/
private List> bacthInsertMap;
/**接受返回的主键ID*/
private Long id;
/**删除字段集合*/
private List> deleteList;
/** 删除的字段名 */
private String deleteCoulumnName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String[] getColumns() {
return columns;
}
public void setColumns(String[] columns) {
this.columns = columns;
}
public String getTables() {
return tables;
}
public void setTables(String tables) {
this.tables = tables;
}
public String getWhereSql() {
return whereSql;
}
public void setWhereSql(String whereSql) {
this.whereSql = whereSql;
}
public List getParamList() {
return paramList;
}
public void setParamList(List paramList) {
this.paramList = paramList;
}
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public String getSortColumn() {
return sortColumn;
}
public void setSortColumn(String sortColumn) {
this.sortColumn = sortColumn;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Map getInsertMap() {
return insertMap;
}
public void setInsertMap(Map insertMap) {
this.insertMap = insertMap;
}
public List> getBacthInsertMap() {
return bacthInsertMap;
}
public void setBacthInsertMap(List> bacthInsertMap) {
this.bacthInsertMap = bacthInsertMap;
}
public List> getDeleteList() {
return deleteList;
}
public void setDeleteList(List> deleteList) {
this.deleteList = deleteList;
}
public String getDeleteCoulumnName() {
return deleteCoulumnName;
}
public void setDeleteCoulumnName(String deleteCoulumnName) {
this.deleteCoulumnName = deleteCoulumnName;
}
}
ParamCondition.java
package com.beijingserver.pojo;
public class ParamCondition {
/**连接符号*/
private String connSymbol;
/**字段名*/
private String column;
/**判断符号*/
private String judgeSymbol;
/**字段等于的值*/
private Object value;
/**结束符号*/
private String symbolEnd;
public String getConnSymbol() {
return connSymbol;
}
public void setConnSymbol(String connSymbol) {
this.connSymbol = connSymbol;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public String getJudgeSymbol() {
return judgeSymbol;
}
public void setJudgeSymbol(String judgeSymbol) {
this.judgeSymbol = judgeSymbol;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getSymbolEnd() {
return symbolEnd;
}
public void setSymbolEnd(String symbolEnd) {
this.symbolEnd = symbolEnd;
}
}
Mybatis配置
classpath:jdbc.properties
jdbc配置
#hibernate.dialect=com.bky.util.Oracle10gDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=Baikeyang)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)))
#jdbc_username=sshe
#jdbc_password=1234
#hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#jdbc_username=sshe
#jdbc_password=1234
#hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#------------此处定义数据库连接------------#
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://192.168.0.40\:3306/XINLANDETESTDB?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull
jdbc.username=devuser
jdbc.dbType=mysql
jdbc.password=devpassword
jdbc.filters=stat
jdbc.maxActive=10000
jdbc.initialSize=3
jdbc.maxWait=60000
jdbc.minIdle=2
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=false
jdbc.maxOpenPreparedStatements=20
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true
#hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/dbName
#jdbc_username=sa
#jdbc_password=123456
#jndiName=java:comp/env/BenDiShuJuYuan
#hibernate.hbm2ddl.auto=update
#hibernate.show_sql=true
#hibernate.format_sql=true
#hibernate.use_sql_comments=true
#sessionInfoName=sessionInfo
#uploadPath=/ssheUpupLoadPath
pom.xml 文件
4.0.0
priv.zhouhuayi.packing
parent
1.0
commondao
priv.zhouhuayi.packing
pojo
${project.version}
org.mybatis
mybatis
${mybatis.version}
mysql
mysql-connector-java
${mysql.version}
com.alibaba
druid
${druid.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-oxm
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-test
${spring.version}
org.mybatis
mybatis-spring
${mybatis-spring.version}
测试类
import javax.annotation.Resource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import priv.zhouhuayi.packing.mapper.common.CommonMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:Mybatis.xml"})
public class CommonDaoTest {
@Resource
private CommonMapper commonMapper;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test() {
System.out.println(commonMapper);
String sql = "select * from manager";
System.out.println(commonMapper.findManyData(sql));
}
}