java – 正确处理返回数据
我正在处理我正在为一个项目写的DAO库的回报的问题.这个图书馆可能会被另一个人使用,我想要正确地做.我应该如何处理我的DAO函数的返回语句?
实施例1 实施例2 实施例3 在我的情况下,什么是“好”的做法或“最好”的做法? 解决方法
看来你的图书馆正在做数据库式的电话.如果是这样,那么我会做的是
JPA 2 specification实现的.
我的意思是,看看JPA API中的find()方法,并返回正是他们在做什么. /** * Find by primary key. * @param entityClass * @param primaryKey * @return the found entity instance or null * if the entity does not exist * @throws IllegalStateException if this EntityManager has been closed. * @throws IllegalArgumentException if the first argument does * not denote an entity type or the second * argument is not a valid type for that * entity's primary key */ public <T> T find(Class<T> entityClass,Object primaryKey); 你可以在find中看到,我认为这与getCustomer()方法类似,如果没有找到,它将返回null,如果参数无效,则只会抛出IllegalArgumentException. 如果find()方法与getCustomer()不相似,则应该实现与getSingleResult()相同的行为: /** * Execute a SELECT query that returns a single result. * @return the result * @throws EntityNotFoundException if there is no result * @throws NonUniqueResultException if more than one result * @throws IllegalStateException if called for a Java * Persistence query language UPDATE or DELETE statement */ public Object getSingleResult(); 如果没有找到结果,则会抛出EntityNotFoundException,如果发现多个实例,则为NonUniqueResultException,如果SQL为错误则为IllegalStateException. 你必须决定哪种行为最适合你. getResultList()也是如此: /** * Execute a SELECT query and return the query results * as a List. * @return a list of the results * @throws IllegalStateException if called for a Java * Persistence query language UPDATE or DELETE statement */ public List getResultList(); 如果没有找到,getResultList()将返回null,如果SQL是非法的则抛出异常. 通过遵循此行为,您是一贯的,您的用户将会了解图书馆的感觉. 一个备用的行为是返回一个空集合而不是null.这是Google Guava如何实现他们的API,这是真正的首选.但是,我喜欢一致性,仍然认为你应该尽可能接近标准来实现图书馆. 资源 Joshua Bloch made a video explaining how to design a good API and why it matters. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |