ORM工具类
package per.nonoas.orm;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class MyOrmUtil<T> {
final protected T selectOne(String sql, Object... params) {
T t = null;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(getSql(sql));
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
if (rs.next())
t = mapToBean(rs, getBeanClass());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null)
ps.close();
if (rs != null)
rs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return t;
}
final protected List<T> select(String sql, Object... params) {
List<T> list = new ArrayList<>(8);
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(getSql(sql));
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
while (rs.next())
list.add(mapToBean(rs, getBeanClass()));
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null)
ps.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (list.size() == 0)
return null;
return list;
}
final protected void insert(String sql, T t) {
try {
beanToDataBase(sql, t);
} catch (SQLException e) {
e.printStackTrace();
}
}
final protected void update(String sql, T t) {
try {
beanToDataBase(sql, t);
} catch (SQLException e) {
e.printStackTrace();
}
}
final protected void delete(String sql, T t) {
try {
beanToDataBase(sql, t);
} catch (SQLException e) {
e.printStackTrace();
}
}
private T mapToBean(ResultSet rs, Class<T> beanClass) {
List<String> list = getColumnNames(rs);
T t = null;
try {
t = beanClass.newInstance();
for (String colName : list) {
String methodName = "set" + firstUpperCase(colName);
Field field = beanClass.getDeclaredField(colName);
Class<?> type = field.getType();
Object value = rs.getObject(colName);
Method method = beanClass.getDeclaredMethod(methodName, type);
if (value != "" && value != null) {
if (value.getClass().getSimpleName().equals("BigDecimal")
&& type.toString().equals("class java.lang.Integer")) {
value = Integer.parseInt(value.toString());
}
} else {
field.getType().cast(value);
}
method.invoke(t, value);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return t;
}
private void beanToDataBase(String sql, T t) throws SQLException {
Class<?> beanClass = t.getClass();
List<String> list = getParms(sql);
sql = getSql(sql);
Connection con = getConnection();
PreparedStatement ps = null;
try {
ps = con.prepareStatement(sql);
for (int i = 0; i < list.size(); i++) {
String colnName = list.get(i);
String methodName = "get" + firstUpperCase(colnName);
Method method = beanClass.getDeclaredMethod(methodName);
Object value = method.invoke(t);
ps.setObject(i + 1, value);
}
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
if (ps != null)
ps.close();
con.close();
}
}
private List<String> getColumnNames(ResultSet rs) {
List<String> list = new ArrayList<>(8);
ResultSetMetaData rsm;
int columnCount;
try {
rsm = rs.getMetaData();
columnCount = rsm.getColumnCount();
for (int i = 0; i < columnCount; i++) {
list.add(rsm.getColumnName(i + 1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
private List<String> getParms(String sql) {
List<String> list = new ArrayList<>(8);
Pattern p = Pattern.compile("[#]\\{\\w*[}]");
Matcher m = p.matcher(sql);
while (m.find()) {
String str = m.group();
String column = str.substring(2, m.group().length() - 1);
list.add(column);
}
return list;
}
private String firstUpperCase(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
private String getSql(String sql) {
return sql.replaceAll(("[#]\\{\\w*[}]"), "?");
}
protected abstract Connection getConnection();
protected abstract Class<T> getBeanClass();
}
DAO抽象类
package indi.nonoas.crm.dao;
import java.sql.Connection;
import indi.nonoas.crm.utils.DBopener;
import per.nonoas.orm.MyOrmUtil;
public abstract class MyDao<T> extends MyOrmUtil<T> {
@Override
protected Connection getConnection() {
return DBopener.getConnection();
}
@Override
protected abstract Class<T> getBeanClass();
}
使用案例
package indi.nonoas.crm.dao;
import java.util.ArrayList;
import indi.nonoas.crm.bean.GoodsBean;
public class GoodsDao extends MyDao<GoodsBean> {
private static final String SELECT_ALL = "select * from goods_info";
private static final String SELECT_BY_FILTRATE = "select * from goods_info where (id like #{id} or name like #{name}) and type like #{type}";
private static final String INSERT_INFO = "insert into goods_info(id,name,sell_price,purchas_price,quantity,min_discount,deduction,deduction_rate,base_unit,type,photo) "
+ "values(#{id},#{name},#{sell_price},#{purchas_price},#{quantity},#{min_discount},#{deduction},#{deduction_rate},#{base_unit},#{type},#{photo})";
private static final String DELETE_BY_ID = "delete from goods_info where id=#{id}";
private static final String UPDATE = "update goods_info set name=#{name},sell_price=#{sell_price},purchas_price=#{purchas_price},quantity=#{quantity},min_discount=#{min_discount},deduction=#{deduction},deduction_rate=#{deduction_rate},base_unit=#{base_unit},type=#{type},photo=#{photo} where id=#{id}";
private static final GoodsDao INSTANCE = new GoodsDao();
private GoodsDao() {
}
public static GoodsDao getInstence() {
return INSTANCE;
}
public ArrayList<GoodsBean> selectAll() {
ArrayList<GoodsBean> list = null;
list = (ArrayList<GoodsBean>) select(SELECT_ALL);
return list;
}
public ArrayList<GoodsBean> selectByFiltrate(String id, String name, String type) {
ArrayList<GoodsBean> list = null;
list = (ArrayList<GoodsBean>) select(SELECT_BY_FILTRATE, id, name, type);
return list;
}
public void deleteByID(GoodsBean bean) {
delete(DELETE_BY_ID, bean);
}
public void insertInfo(GoodsBean bean) {
insert(INSERT_INFO, bean);
}
public void update(GoodsBean goodsBean) {
update(UPDATE, goodsBean);
}
@Override
protected Class<GoodsBean> getBeanClass() {
return GoodsBean.class;
}
}