MyAatis 类
package kj15.frame;
import kj15.ann.Date;
import kj15.ann.Id;
import kj15.dao.BaseDao;
import kj15.until.Tool;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyAatis<T> extends BaseDao {
//id问题,代码冗余问题,数据库灵活性的问题
private Class<T> tclass;
@Override
public Connection getCon() {
// TODO Auto-generated method stub
try {
return super.getCon();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
// TODO Auto-generated method stub
super.close(connection, statement, resultSet);
}
public boolean addOne(T t) throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
try {
StringBuilder sb = new StringBuilder("insert into ");
//Grade(gradeName)value(?)
Class<? extends Object> class1 = t.getClass();
sb.append(class1.getSimpleName()).append("(");
Field[] declaredFields = class1.getDeclaredFields();
if (declaredFields == null || declaredFields.length == 0) {
return false;
}
for (Field field : declaredFields) {
if (field.getAnnotation(Id.class) != null) {
continue;
}
sb.append(Tool.humpToLine2(field.getName())).append(",");
}
sb.delete(sb.length() - 1, sb.length());
sb.append(")value(");
for (Field field : declaredFields) {
if (field.getAnnotation(Id.class) != null) {
continue;
}
Object object = fieldToObject(field, t);
sb.append("'").append(object).append("'").append(",");
}
sb.delete(sb.length() - 1, sb.length());
sb.append(")");
Boolean x = getBooleanFromSql(prepareStatement, sb, connection);
return x;
} catch (Exception e) {
e.printStackTrace();
// TODO Auto-generated catch block
} finally {
close(connection, prepareStatement, null);
}
return false;
}
private Boolean getBooleanFromSql(PreparedStatement prepareStatement, StringBuilder sb, Connection connection) throws Exception {
prepareStatement = connection.prepareStatement(sb.toString());
int result = prepareStatement.executeUpdate();
if (result > 0) {
return true;
}
return false;
}
public boolean deleteOneById(Integer id) throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
try {
StringBuilder sb = new StringBuilder("delete from ");
//Grade(gradeName)value(?) name = new ();
String simpleName = tclass.getSimpleName();
Field[] declaredFields = tclass.getDeclaredFields();
boolean flag = false;//看表有没有加主键注解
for (Field field : declaredFields) {
if (field.getAnnotation(Id.class) != null) {
sb.append(simpleName).append(" where " + field.getName() + "=" + id);
flag = true;
}
}
if (!flag) {
throw new Exception("表没主键注解,去加注解去");
}
return getBooleanFromSql(prepareStatement, sb, connection);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, prepareStatement, null);
}
return false;
}
public boolean update(T t) throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
try {
StringBuilder sb = new StringBuilder("update ");
//Grade(gradeName)value(?)
Class<? extends Object> class1 = t.getClass();
sb.append(class1.getSimpleName()).append(" set ");
Field[] declaredFields = class1.getDeclaredFields();
if (declaredFields == null || declaredFields.length == 0) {
return false;
}
for (Field field : declaredFields) {
if (field.getAnnotation(Id.class) != null) {
continue;
}
sb.append(field.getName()).append("=");
Object object = fieldToObject(field, t);
sb.append("'").append(object).append("'").append(",");
}
sb.delete(sb.length() - 1, sb.length());
boolean flag = false;//看表有没有加主键注解
for (Field field : declaredFields) {
field.setAccessible(true);
if (field.getAnnotation(Id.class) != null) {
sb.append(" where " + field.getName() + "=" + field.get(t));
flag = true;
}
}
if (!flag) {
throw new Exception("表没主键注解,去加注解去");
}
return getBooleanFromSql(prepareStatement, sb, connection);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, prepareStatement, null);
}
return false;
}
public List<T> queryAll() throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
ResultSet executeQuery = null;
List<T> list = new ArrayList<>();
try {
prepareStatement = connection.prepareStatement("select * from " + tclass.getSimpleName());
executeQuery = prepareStatement.executeQuery();
list = putResult(executeQuery, tclass);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, prepareStatement, executeQuery);
}
return list;
}
public T queryOneById(Integer id) throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
ResultSet executeQuery = null;
try {
StringBuilder sb = new StringBuilder("select * from ");
sb.append(tclass.getSimpleName());
Field[] declaredFields = tclass.getDeclaredFields();
boolean flag=false;
for (Field declaredField : declaredFields) {
if (declaredField.getAnnotation(Id.class) != null) {
sb.append(" where " +Tool.humpToLine2(declaredField.getName()) + "="+ id);
flag=true;
}
}
if(flag==false){
throw new Exception("没有主键注解");
}
System.out.println(sb);
prepareStatement = connection.prepareStatement(sb.toString());
executeQuery = prepareStatement.executeQuery();
ArrayList<T> ts = putResult(executeQuery, tclass);
close(connection, prepareStatement, null);
return ts.get(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, prepareStatement, executeQuery);
}
return null;
}
public List<T> QueryOneByCondition(HashMap<String, String> map) throws Exception {
Connection connection = getCon();
PreparedStatement prepareStatement = null;
T newInstance = null;
ResultSet executeQuery = null;
StringBuilder sb = new StringBuilder("select * from ");
List<T> list = new ArrayList<>();
try {
sb.append(tclass.getSimpleName()).append(" where ");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(Tool.humpToLine2(entry.getKey()) + "='" + entry.getValue() + "' and ");
}
String sbl = sb.toString();
String substring = sbl.substring(0, sbl.length() - 4);
prepareStatement = connection.prepareStatement(substring);
executeQuery = prepareStatement.executeQuery();
list = putResult(executeQuery, tclass);
close(connection, prepareStatement, null);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, prepareStatement, executeQuery);
}
return list;
}
public MyAatis(Class<T> tclass) {
super();
this.tclass = tclass;
}
public static <T> ArrayList<T> putResult(ResultSet rs, Class<T> obj) throws Exception {
ArrayList<T> arrayList = new ArrayList<T>();
ResultSetMetaData metaData = rs.getMetaData();
//获取总列数,确定为对象赋值遍历次数
int count = metaData.getColumnCount();
while (rs.next()) {
// 创建对象实例
T newInstance = obj.newInstance();
// 开始为一个对象赋值
for (int i = 1; i <= count; i++) {
// 给对象的某个属性赋值
String name = metaData.getColumnName(i).toLowerCase();
// 改变列名格式成java命名格式
name = Tool.lineToHump(name);
// 首字母大写
String substring = name.substring(0, 1);
String replace = name.replaceFirst(substring, substring.toUpperCase());
// 获取字段类型
Class<?> type = obj.getDeclaredField(name).getType();
Method method = obj.getMethod("set" + replace, type);
//判断读取数据的类型
if (type.isAssignableFrom(String.class)) {
method.invoke(newInstance, rs.getString(i));
} else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) {
method.invoke(newInstance, rs.getInt(i));
} else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
method.invoke(newInstance, rs.getBoolean(i));
} else if (type.isAssignableFrom(java.util.Date.class)) {
method.invoke(newInstance, rs.getDate(i));
} else if (type.isAssignableFrom(BigDecimal.class)) {
method.invoke(newInstance, rs.getBigDecimal(i));
} else if (type.isAssignableFrom(Double.class)) {
method.invoke(newInstance, rs.getDouble(i));
} else if (type.isAssignableFrom(Long.class)) {
method.invoke(newInstance, rs.getLong(i));
} else if (type.isAssignableFrom(Float.class)) {
method.invoke(newInstance, rs.getFloat(i));
}
}
arrayList.add(newInstance);
}
return arrayList;
}
private Object fieldToObject(Field field,Object t) throws Exception {
if (field.getAnnotation(Id.class) != null) {
return null;
}
field.setAccessible(true);
Object object = null;
if (field.getAnnotation(Date.class) != null) {
java.util.Date date = (java.util.Date) field.get(t);
String pattern = field.getAnnotation(Date.class).pattern();
SimpleDateFormat format = new SimpleDateFormat(pattern);
object = format.format(date);
} else {
object = field.get(t);
}
return object;
}
}
Basedao类
package kj15.dao.inter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;
import java.sql.PreparedStatement;
public interface IBaseDao {
Connection getCon() throws NullPointerException, IOException;
void close(Connection connection,
PreparedStatement statement,
ResultSet resultSet);
}
package kj15.dao;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.sql.PreparedStatement;
import kj15.dao.inter.IBaseDao;
public class BaseDao implements IBaseDao {
@Override
public Connection getCon() throws NullPointerException, IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Properties properties = new Properties();
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("myAatis.properties");
properties.load(resourceAsStream);
String url = properties.getProperty("url");
String userName = properties.getProperty("userName");
String pw = properties.getProperty("pw");
return DriverManager.getConnection(url, userName, pw);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
// TODO Auto-generated method stub
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
myAatis.properties配置
url=jdbc:mysql://localhost:3306/kj15?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
userName=root
pw=123qwe
Date注解
package kj15.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Date {
String pattern() default "";
}
package kj15.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Id {
}