反射泛型,Dao设计模型 (编码时需要用到)
Dao
package com.xiaofan.reflect; import java.io.Serializable; public interface Dao<T> { /** * 添加实体(Entity--Domain)数据到数据库中 * @param t */ void save(T t); /** * 修改数据库中的实体 * @param t */ void update(T t); /** * 根据主键删除记录 * @param pk */ void delete(Serializable pk); /** * 根据主键查询一条记录 * @param pk * @return */ T find(Serializable pk); }
DAOBase
package com.xiaofan.reflect; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import org.hibernate.Session; public abstract class DAOBase<T> implements Dao<T> { private Session session; private Class clazz; //反射泛型 public DAOBase(){ Class clz = this.getClass();//具体的Dao实现类 com.xiaofan.reflect.BookDaoImpl // System.out.println(clz.getName()); ParameterizedType pt = (ParameterizedType)clz.getGenericSuperclass();// DAOBase<Book> // System.out.println(pt); clazz = (Class)pt.getActualTypeArguments()[0];// Book.class // System.out.println(clazz); } public void save(T t) { session.save(t); } public void update(T t) { session.update(t); } public void delete(Serializable pk) { T t = (T)session.get(clazz, pk); session.delete(t); } public T find(Serializable pk) { return (T)session.get(clazz, pk); } }
BookDao
package com.xiaofan.reflect; public interface BookDao extends Dao<Book>{ /** * 根据条件查询 * @param where */ void queryByCondition(String where); }
BookDaoImpl
package com.xiaofan.reflect; public class BookDaoImpl extends DAOBase<Book> implements BookDao{ public void queryByCondition(String where) { } }
Book
package com.xiaofan.reflect; public class Book { }
CustomerDao
package com.xiaofan.reflect; public interface CustomerDao extends Dao<Customer>{ }
CustomerDaoImpl
package com.xiaofan.reflect; public class CustomerDaoImpl extends DAOBase<Customer> implements CustomerDao { }
Customer
package com.xiaofan.reflect; public class Customer { }
Client
package com.xiaofan.reflect; public class Client { public static void main(String[] args) { BookDao bDao = new BookDaoImpl(); bDao.queryByCondition("condition"); CustomerDao cDao = new CustomerDaoImpl(); cDao.find(001); } }