Hibernate:JDBC与批量记录中的Hibernate性能

时间:2015-08-05 11:52:51

标签: java performance hibernate jdbc orm

说明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 方法将返回给定LoadoutOperatingSession的所有loadoutId个对象

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解决方案更有效吗?

请证明。

1 个答案:

答案 0 :(得分:2)

使用此SQL语句可以对数据库级别执行检查:

select top 1 a.id 
from LoadoutOperatingSession a, LoadoutOperatingSession b 
where a.FROM_DATE <= b.TO_DATE and b.FROM_DATE <= a.TO_DATE

为什么它更快:

  • 与应用程序级别相同。 SQL返回第一个重叠记录
  • 但是,您没有从DB返回记录列表,而是简单的整数 - 没有序列化开销

但是,如果在验证从DB读取的记录后在应用程序级别上抛出IllegalArgument,我认为还有其他问题。我不知道你的用例,但是防止保存这些记录会更安全

修改

我之前的回答不正确。这是在DB级别上完成的相等检查

select top 1 a.id 
from LoadoutOperatingSession a 
where a.FROM_DATE <= :insertedStartDate and a.TO_DATE >= :insertedEndDate