通过反射封装JDBC
具体上代码我的BaseDao:
public class BaseDao<T> {
private Class clazz;
private Properties pro=null;
public BaseDao(){
ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass(); //按英译意思是获取这个类的泛型父类
clazz=(Class) pt.getActualTypeArguments()[0]; //得到真实的类型内容
pro=MainKey.getMainKeyType(clazz); //静态方法获取的是每个实体类的类名(相当于数据库里的表明)和数据库里的主键自动增长列
}
//返回数据库连接
private Connection getConnection() throws IOException{
try {
Properties pro=new Properties();
pro.load(BaseDao.class.getClassLoader().getResourceAsStream("config.Properties")); //我的连接数据库配置文件
Class.forName(pro.getProperty("driver"));
return DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("user"), pro.getProperty("pwd"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 添加
* @param t
* 要保存的类
* @return 成功返回true/失败返回false
*/
public boolean save(T t){
Connection con=null;
try {
con = getConnection();
Field[] filds=clazz.getDeclaredFields(); //获取公开的字段包括私有
StringBuffer sb=new StringBuffer();
sb.append("INSERT INTO ["+t.getClass().getSimpleName()+ "](");
for (Field field : filds) {
if(field.getName().equals(pro.getProperty("idname"))){
continue;
}
sb.append(field.getName()+",");
}
sb.deleteCharAt(sb.length()-1);
sb.append(")VALUES(");
List<Object> prams=new ArrayList<Object>();
for (Field field : filds) {
if(field.getName().equals(pro.getProperty("idname"))){
continue;
}
PropertyDescriptor pd=new PropertyDescriptor(field.getName(),clazz);
Method mt=pd.getReadMethod();
Object obj=mt.invoke(t);
prams.add(obj);
sb.append("?,");
}
sb.deleteCharAt(sb.length()-1);
sb.append(")");
PreparedStatement ps=con.prepareStatement(sb.toString(),Statement.RETURN_GENERATED_KEYS); //Statement.RETURN_GENERATED_KEYS可以获
//得自增列的id号
for (int i = 0; i < prams.size(); i++) {
ps.setObject(i+1,prams.get(i));
}
int count=ps.executeUpdate();
ResultSet rs=ps.getGeneratedKeys(); //在这里可以把自增列的ID号读出来
if(rs.next()){
System.out.println("key:"+rs.getInt(1));
}
if(count>0){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
/**
* 删除
* @param ser 参数
* @return 成功返回true/失败返回false
*/
public boolean delete(Serializable ser){
Connection con=null;
try {
con=getConnection();
String sql="DELETE FROM"+pro.getProperty("tableName")+" where "+pro.getProperty("idname")+"=?";
PreparedStatement ps=con.prepareStatement(sql);
ps.setObject(1,ser);
int count=ps.executeUpdate();
if(count>0){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
/**
* 更新
* @param t要更新的类
* @return 成功返回true/失败返回false
*/
public boolean update(T t){
Connection con=null;
try {
con=getConnection();
StringBuffer sb=new StringBuffer();
sb.append("UPDATE"+pro.getProperty("tableName")+"set");
Field[] fields=clazz.getDeclaredFields();
List<Object> prams=new ArrayList<Object>();
for (Field field : fields) {
if(pro.getProperty("idname").equals(field.getName())){
continue;
}
sb.append(" "+field.getName()+"=?,");
PropertyDescriptor pd=new PropertyDescriptor(field.getName(), clazz);
Method mt=pd.getReadMethod();
Object obj=mt.invoke(t);
prams.add(obj);
}
sb.deleteCharAt(sb.length()-1);
sb.append(" where "+pro.getProperty("idname")+"=?");
PropertyDescriptor pd=new PropertyDescriptor(pro.getProperty("idname"), clazz);
Method mt=pd.getReadMethod();
Object obj=mt.invoke(t);
prams.add(obj);
PreparedStatement ps=con.prepareStatement(sb.toString());
for (int i = 0; i < prams.size(); i++) {
ps.setObject(i+1,prams.get(i));
}
int count=ps.executeUpdate();
if(count>0){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
/**
* 查询所有
* @return 实体类集合
*/
public List<T> findAll(){
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=getConnection();
String sql="select * from"+pro.getProperty("tableName");
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
List<T> list=new ArrayList<T>();
while(rs.next()){
T t=(T) clazz.newInstance();
Map<String,Field> map=new HashMap<String, Field>();
for (Field field : clazz.getDeclaredFields()) {
map.put(field.getName(),field);
}
int count=rs.getMetaData().getColumnCount();//每行多少列
for (int i = 0; i < count; i++) {
try {
Field field=map.get(rs.getMetaData().getColumnName(i+1).toLowerCase());
field.setAccessible(true);
if (field.getType().getName().equals(int.class.getName())|| field.getType().getName().equals(Integer.class.getName())) {
field.set(t, Integer.valueOf(rs.getObject(i + 1).toString()));
} else if (field.getType().getName().equals(Date.class.getName())) {
field.set(t, new Date(rs.getDate(i + 1).getTime()));
} else if (field.getType().getName().equals(Double.class.getName())|| field.getType().getName().equals(double.class.getName())) {
field.set(t, rs.getDouble(i + 1));
} else if (field.getType().getName().equals(
String.class.getName())) {
field.set(t, rs.getObject(i + 1).toString());
} else {
field.set(t, rs.getObject(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
****************************************************************************************************************************
每个实体类都配置了个Properties:用来存放每个实体类的类名(相当于数据库里的表明)和数据库里的主键自动增长列
tableName=[user]
MainKeyType=identity
idname=id
***********************************************
我的UserDao只要继承BaseDao就行:
public class UserDao extends BaseDao<User>
**********************************************
我的工具类用来返回 读取每个实体类的类名(相当于数据库里的表明)和数据库里的主键自动增长列的Properties:
public class MainKey {
public static Properties getMainKeyType(Class clazz){
Properties pro=new Properties();
String path=clazz.getName().replace(".", "/")+".Properties";
System.out.println(path);
try {
pro.load(MainKey.class.getClassLoader().getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
return pro;
*******************************************************
Main方法测试:
public static void main(String[] args) throws IOException {
UserDao ud=new UserDao();
User user=new User();
user.setId(2);
user.setAge(22);
user.setName("sp");
user.setPhone(138438);
ud.save(user);
// ud.update(user);
// System.out.println(ud.delete(1));
//MainKey.getMainKeyType(User.class);
}
}
}