【发布时间】:2015-08-05 11:52:51
【问题描述】:
描述:LoadoutOperatingSession代表一个特定的时间段,属于某个loadoutId。可以有很多LoadoutOperatingSession对象具有相同的loadoutId
在插入新会话之前,必须检查是否存在重叠。
下面是我设计的模型对象。
public class LoadoutOperatingSession extends Entity implements Serializable, Comparable<LoadoutOperatingSession>{
private Long loadoutId;
private Date effectiveFromDate;
private Date effectiveToDate;
private String sessionStartTime;
private String sessionEndTime;
private String isSchedule;
/**
* Compares the given session with the current one and return 1 if this session is greater than the given session,
* -1 if the this session is less than the given session and
* 0 is the sessions are overlapping.
*
* @param session1
* First Session
*
* @param session
* Second Session
*/
@Override
public int compareTo(LoadoutOperatingSession session) {
if (session.getEffectiveToDate().getTime() < this.getEffectiveFromDate().getTime()) {
return 1;
} else if (this.getEffectiveToDate().getTime() < session.getEffectiveFromDate().getTime()) {
return -1;
} else if (this.getEffectiveFromDate().getTime() == session.getEffectiveFromDate().getTime()) {
int thisStartTime = Integer.parseInt(this.getSessionStartTime());
int thisEndTime = Integer.parseInt(this.getSessionEndTime());
int sessionStartTime = Integer.parseInt(session.getSessionStartTime());
int sessionEndTime = Integer.parseInt(session.getSessionEndTime());
if (thisEndTime < sessionStartTime) {
return -1;
} else if (thisStartTime > sessionEndTime) {
return 1;
}
return 0;
}
return 0;
}
}
假设有很多 LoadoutOperatingSession 对象具有相同的 loadoutId。
为了检查重叠,我获取了所有LoadoutOperatingSession 对象并使用compareTo 方法相互比较。
注意:此检查在持久化当前会话之前完成。
fetchLoadoutOperatingSessionsList 方法将返回给定loadoutId 的所有LoadoutOperatingSession 对象
validateForOverlappings(model, fetchLoadoutOperatingSessionsList(model));
private <T extends Comparable> void validateForOverlappings(T obj, List<T> objList){
for (Comparable c : objList) {
if(obj.compareTo((T) c) == 0){
throw new IllegalArgumentException("Overlapping Sessions are not allowed!");
}
}
}
问题:同样的验证可以通过执行 JDBC 查询并计算重叠会话数来完成。
会比上面提到的java解决方案更高效吗?
请说明理由。
【问题讨论】:
标签: java performance hibernate jdbc orm