DAO层有很多操作其实可以用范式加反射来实现的,所以我就开始构想我的万金油BaseDAO了。
BaseHibernateDaoAdvance.java
public class BaseHibernateDaoAdvance<T extends ModifyInfoEntity, PK extends Serializable, DTO extends BaseDto> extends HibernateDaoSupport implements BaseDaoAdvance<T, PK, DTO> { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private void getSessionFactory(SessionFactory sessionFactory){ super.setSessionFactory(sessionFactory); } // 实体类类型(由构造方法自动赋值) private Class<T> entityClass; private Class<DTO> dtoClass; // 构造方法,根据实例类自动获取实体类类型 public BaseHibernateDaoAdvance() { System.out.println("-------------->in BaseHibernateDaoAdvance"); this.entityClass = null; Class c = getClass(); System.out.println(c); Type t = c.getGenericSuperclass(); System.out.println(t); if (t instanceof ParameterizedType) { System.out.println("in if"); Type[] p = ((ParameterizedType) t).getActualTypeArguments(); System.out.println(Arrays.toString(p)); this.entityClass = (Class<T>) p[0]; this.dtoClass = (Class<DTO>) p[2]; } } }
写好,准备些测试类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/config/applicationContext.xml", "classpath:/config/service.xml","classpath:/config/dao.xml" }) public class BaseDAOImplAdvanceTest { private BaseDaoAdvance<Course, Serializable, CourseDTO> baseDAOImpl; public BaseDaoAdvance<Course, Serializable, CourseDTO> getBaseDAOImpl() { return baseDAOImpl; } @Autowired public void setBaseDAOImpl( BaseDaoAdvance<Course, Serializable, CourseDTO> baseDAOImpl) { this.baseDAOImpl = baseDAOImpl; } @Test public void queryList(){ CourseDTO dto = new CourseDTO(); baseDAOImpl.queryList(dto); System.out.println("here-------------------->"); } }
但是提示错误java.lang.NullPointerException
了解一下代码,发现应该是这一段判断不通过
if (t instanceof ParameterizedType) { System.out.println("in if"); Type[] p = ((ParameterizedType) t).getActualTypeArguments(); System.out.println(Arrays.toString(p)); this.entityClass = (Class<T>) p[0]; this.dtoClass = (Class<DTO>) p[2]; }
去掉if测试一下,还是报错,java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
~~~~(>_<)~~~~
其实原因是因为范式的使用方式不对。
增加了具体的DAO和实现
public interface CourseDao extends BaseDaoAdvance<Course, Serializable,CourseDTO> { }
@Repository public class CourseDaoImpl extends BaseHibernateDaoAdvance<Course, Serializable,CourseDTO> implements CourseDao { }
测试类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/config/applicationContext.xml", "classpath:/config/service.xml","classpath:/config/dao.xml" }) public class CourseDaoImplTest { // private BaseDaoAdvance<Course, Serializable, CourseDTO> baseDAOImpl; @Autowired private CourseDao courseDao; @Test public void queryList(){ CourseDTO dto = new CourseDTO(); courseDao.queryList(dto); System.out.println("here-------------------->"); } }
OK,成功!
范式应该在编译的时候就指定,而不是运行时。
时间: 2024-10-06 01:14:55