hibernate封装的add()如下
public static Object add(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(entity);
tx.commit();
return entity;
} finally {
if (s != null)
s.close();
}
}
for(int j=0;j<softwareUnits.size();j++){ --list中有两个数据,要将这两条数据保存到数据库
SoftwareUnit softwareUnit = softwareUnits.get(j);
//根据name值判断重名
hql = "from StaticRequirementsTrace where softwareUnitName= '"+softwareUnit.getSoftwareunitname()+"' and sectionId = '"+section.getSectionId()+"'";
List<StaticRequirementsTrace> staticRequirementsTraces = HibernateUtil.getListByHql(hql);
//如果能查到说明数据库有重名,则不需要在重新加
if(staticRequirementsTraces.size()== 0){
StaticRequirementsTrace staticRequirementsTrace = new StaticRequirementsTrace();
staticRequirementsTrace.setSoftwareUnitName(softwareUnit.getSoftwareunitname());
staticRequirementsTrace.setSectionId(section.getSectionId());
HibernateUtil.add(staticRequirementsTrace);
}
}
问题是:for连续调用两遍,两遍里的数据是相同的,代码走完之后发现数据库是有四条数据,意思就是重名判定失效,如果我debug调试的话就不会出现这个问题,一切很正常,代码走第二遍的时候判重名时能在数据库查到。
求解释 为什么不debug的话会有四条数据。
------解决方案--------------------
hql = "from StaticRequirementsTrace where softwareUnitName= '"+softwareUnit.getSoftwareunitname()+"' and sectionId = '"+section.getSectionId()+"'";
注意 and和section.getSectionId(),这个值存在么?