让我说我有以下数据库结构:
以红色显示表格,以黑色显示字段
结构使用 StructureLocationType
链接到 LocationType现在我需要获取属于LocationType的结构的列表:
// get LocationType
LocationTypeEntity locationTypeEntity = databaseManager.selectLocationType(session, locationTypeID);
// get list of StructureLocationType(s)
List<StructureLocationTypeEntity> structureLocationTypeEntities = databaseManager.selectStructureLocationTypes(session, locationTypeID);
// get list of Structures(s)
List<StructureEntity> structures = new ArrayList<>();
for (StructureLocationTypeEntity structure: structureLocationTypeEntities)
{
structures.add(databaseManager.selectStructure(session, structure.getStructureId()));
}
return structures;
我的助手方法使用休眠模式检索数据:
public LocationTypeEntity selectLocationType(Session session, int id)
{
session.beginTransaction();
LocationTypeEntity locationTypeEntity = session.get(LocationTypeEntity.class, id);
session.getTransaction().commit();
return locationTypeEntity;
}
public List<StructureLocationTypeEntity> selectStructureLocationTypes(Session session, int locationTypeId)
{
session.beginTransaction();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<StructureLocationTypeEntity> query = builder.createQuery(StructureLocationTypeEntity.class);
Root<StructureLocationTypeEntity> root = query.from(StructureLocationTypeEntity.class);
query.select(root).where(builder.equal(root.get("locationTypeId"), locationTypeId));
Query<StructureLocationTypeEntity> q = session.createQuery(query);
List<StructureLocationTypeEntity> locationTypeEntities = q.getResultList();
session.getTransaction().commit();
return locationTypeEntities;
}
public StructureEntity selectStructure(Session session, int structureID)
{
session.beginTransaction();
StructureEntity structure = session.get(StructureEntity.class, structureID);
session.getTransaction().commit();
return structure;
}
因此,它似乎已经无效,但是假设有3个 Structures 与 LocationType 链接,则大约需要1200ms的时间来获取Structures的列表。我正在使用它进行自动化测试,因此从理论上讲确实需要提高速度,但是我相信我需要改进它,如果有人可以帮助我改进代码以仅通过单个查询执行它,将不胜感激? (现在很明显它将向数据库发送多个查询)
谢谢。
答案 0 :(得分:1)
找到了一个解决方案,实际上非常简单(没有意识到)
使用JOIN关键字并执行单个本机查询:
Query q = session.createNativeQuery("Select *, StatusId \n" +
"FROM dbo.Structure AS S\n" +
"JOIN dbo.StructureLocationType AS SLT ON SLT.StructureId = S.Id\n" +
"WHERE SLT.LocationTypeId = 1080").addEntity(StructureEntity.class);
List<StructureEntity> zones2 = q.list();
在这种情况下,“ 1080”是我的LocationType ID。