1.引入几个注解,用于处理Java类名与数据表、Java类属性字段与数据库列名不同的情况
package annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value() default "";
}
package annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
String value() default "";
}
package annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Relation {
String value() default "";
}
package annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String value() default "";
}
2.封装Dao底层工具类
package utils;
import annotion.Column;
import annotion.Id;
import annotion.Relation;
import annotion.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DaoUtil{
private static final Logger logger = LoggerFactory.getLogger(DaoUtil.class);
public static<T> T query(Class<T> clazz , String sql, Object... params) {
T t = null;
Map<String,String> map = getNameAndValue(clazz);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ConnUtil.getConnection();
ps = conn.prepareStatement(sql);
if(params!=null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
if(rs.next()){
t= clazz.newInstance();
t = DaoUtil.newInstance(t,rs,clazz);
}
logger.info("调用query方法执行的SQL语句为:"+sql);
} catch (SQLException | InstantiationException | IllegalAccessException e) {
logger.error("DaoUtil中的query方法异常",e);
throw new RuntimeException("DaoUtil中的query方法异常");
}finally {
ConnUtil.close(conn, ps, rs);
}
return t;
}
public static<T> List<T> queryList(Class<T> clazz , String sql, Object... params) {
T t = null;
List<T> list = new ArrayList<>();
Map<String,String> map = getNameAndValue(clazz);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ConnUtil.getConnection();
ps = conn.prepareStatement(sql);
if(params!=null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
while(rs.next()){
t= clazz.newInstance();
t = DaoUtil.newInstance(t,rs,clazz);
list.add(t);
}
logger.info("调用queryList方法执行的SQL语句为:"+sql);
} catch (SQLException | InstantiationException | IllegalAccessException e) {
logger.error("DaoUtil中的queryList方法异常",e);
throw new RuntimeException("DaoUtil工具类queryList方法异常");
}finally {
ConnUtil.close(conn, ps, rs);
}
return list;
}
public static boolean update(String sql, Object...params) {
Connection conn = ConnUtil.getConnection();
PreparedStatement stmt = null;
System.out.println("SQL语句为:"+sql);
try {
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql);
if(params!=null){
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
}
stmt.executeUpdate();
conn.commit();
logger.info("update方法执行的SQL语句为:"+sql);
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException ex) {
logger.error("DaoUtil的update方法中的回滚操作异常",ex);
}
logger.error("DaoUtil的update方法异常",e);
}finally {
ConnUtil.close(conn, stmt, null);
}
return true;
}
public static Object getOne(String sql, Object... params) {
Object obj = null;
Connection conn = ConnUtil.getConnection();
ResultSet rs = null;
PreparedStatement stmt =null;
try {
stmt = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
if (params != null && params[0] != null) {
stmt.setObject(i + 1, params[i]);
}
}
conn.setAutoCommit(false);
rs = stmt.executeQuery();
if(rs.next()){
obj = rs.getObject(1);
}
logger.info("调用getOne方法执行的SQL语句为:"+sql);
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException ex) {
logger.error("DaoUtil的getOne方法中的回滚操作异常",ex);
}
logger.error("DaoUtil类getOne方法异常",e);
}finally {
ConnUtil.close(conn, stmt, rs);
}
return obj;
}
public static Map<String,String> getNameAndValue(Class clazz){
Map<String,String> map = new HashMap<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field :fields){
if (field.isAnnotationPresent(Column.class)){
String name = field.getAnnotation(Column.class).value();
if(name==null||name.equals("")){
name = field.getName();
}
map.put(name, field.getName());
}else if(field.isAnnotationPresent(Relation.class)){
String name = field.getAnnotation(Relation.class).value();
map.put(name, field.getName());
}else if(field.isAnnotationPresent(Id.class)){
String id = field.getAnnotation(Id.class).value();
if(id==null||id.equals("")){
id = field.getName();
}
map.put(id, field.getName());
}else{
map.put(field.getName(), field.getName());
}
}
return map;
}
public static String getTable(Class clazz){
String tableName = "";
if(clazz.isAnnotationPresent(Table.class)){
Table table = (Table) clazz.getAnnotation(Table.class);
tableName = table.value();
}else{
tableName = clazz.getSimpleName();
}
return tableName;
}
public static String getPK(Class clazz){
String id = null;
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
if(field.isAnnotationPresent(Id.class)){
id = field.getAnnotation(Id.class).value();
if(id==null||id.equals("")){
id = field.getName();
}
break;
}
}
return id;
}
public static String getRelation(Class clazz){
String relation ="";
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
if(field.isAnnotationPresent(Relation.class)){
relation = field.getAnnotation(Relation.class).value();
break;
}
}
return relation;
}
public static <T> T newInstance(T t,ResultSet rs,Class clazz){
Map<String,String> map = getNameAndValue(clazz);
String rtable = null;
try{
for(String key:map.keySet()){
Field field = clazz.getDeclaredField(map.get(key));
field.setAccessible(true);
if(field.isAnnotationPresent(Relation.class)){
Class rClass = field.getType();
if(rtable==null){
rtable = getTable(rClass);
}
Object object = rClass.newInstance();
Field[] fields = rClass.getDeclaredFields();
for(Field rField : fields){
if(rField.isAnnotationPresent(Id.class)){
rField.setAccessible(true);
rField.set(object, rs.getObject(key));
break;
}
}
field.set(t,object);
}else{
field.set(t, rs.getObject(key));
}
}
}catch (NoSuchFieldException | InstantiationException | SQLException | IllegalAccessException e){
logger.error("DaoUtil类newsInstance方法异常",e);
}
return t;
}
}