PART 01
1. BASEDAO
package com.atguigu.myssm.basedao;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* @author crystal
* @create 2022-11-09 7:48
*/
public abstract class BaseDAO<T> {
// 获取连接
public Connection getConnection(){
Connection conn = null;
try {
InputStream in = BaseDAO.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(in);
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void closeResource(Connection conn,PreparedStatement ps,ResultSet rs){
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 更新
public int update(String sql,Object...args) {
int val = 0;
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1,args[i]);
}
val = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeResource(conn,ps,null);
}
return val;
}
Class<T> clazz = null;
public BaseDAO(){
Type genericSuperclass = this.getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
Type[] arguments = paramType.getActualTypeArguments();
clazz = (Class<T>) arguments[0];
}
// 查询单条
public T queryOne(String sql,Object ...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1,args[i]);
}