假设我有以下数据库结构:
java - Hibernate结合多个查询-LMLPHP
你可以看到红色的桌子,黑色的田野
结构使用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;

我的助手使用hibernate检索数据的方法:
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个结构与locationtype相关,则需要大约1200毫秒才能得到结构列表。我正在使用它进行自动化测试,所以理论上它确实需要光速,但我相信我需要改进它,如果有人能帮助我改进我的代码,也许可以用一个查询来执行它,我会很感激吗?(现在很明显,它向数据库发送了多个查询)
谢谢您。

最佳答案

找到了一个解决方案,其实很简单(不知道)
使用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”是我的位置类型ID。

10-08 13:35