在 spring-mvc 应用程序中使用未映射的 @JoinTable 和休眠查询 @ManyToMany

Querying @ManyToMany with unmapped @JoinTable with hibernate in a spring-mvc app

我有两个实体。 (Find code below)

我正在尝试编写一个查询,计算与特定 idEntityB 关联的 EntitiesAcustomDetails=:myCriteria

我已经使用读取 associated_entitites table 的 session.CreateSQLQuery 编写了必要的查询,但是,我无法使用它,因为 customDetails 列已被加密hibernate 的 @ColumnTransformer 和 returns 一个 BLOB。而且我无法在 HQL 中复制它,因为 associated_entities 未映射。

a

@Entity
public class entityA{


@Id
private int id;

@Column
@ColumnTransformer
private CustomDetails customDetails;

@ManyToMany(fetch = FetchType.EAGER,
        cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
        },
        mappedBy = "entitiesA")
private List<entityB> entitiesB;

//getters and setters
}

b

@Entity
public class entityB{


@Id
private int id;

@JoinTable(name = "associated_entities",
        joinColumns = { @JoinColumn(name = "entityA_id") },
        inverseJoinColumns = { @JoinColumn(name = "entityB_id") })
private List<EntityA> entitiesA;

//getters and setters
}

我找到了解决方案,但并不理想,因为逻辑不是由 hibernate 完成的。必须在 DAOImpl.

中编写逻辑

示例代码:

public Long getQuery(String criteria, String, fromdate, String todate){
    Query theQuery = currentSession.createQuery(
                    "from EntityA a "+
                    "where a.CustomDetails >= :from "+
                    "and a.CustomDetails <= :to");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            LocalDate From = LocalDate.parse(fromDate, formatter);
            LocalDate To = LocalDate.parse(toDate, formatter);
            theQuery.setParameter("from", From);
            theQuery.setParameter("to", To);
            Long count = (long)0;
            List<EntityA> entities= theQuery.list();
            for(EntityA EA:entities) {
                for(EntityB EB: EA.getEntityB()) {
                    if(EB.someValue().equals(criteria)) count++;
                }
            }
            return count;

我发现的另一个解决方案是更受欢迎的,因为逻辑是由休眠执行的,我发现它要快得多,是使用两个单独的查询和利用 where :foo in elements()

下面的代码示例(不是匹配问题示例,但elements()的思路和用法应该很清楚)

Query<Object1> q1 = currentSession.createQuery("from Object1 o where o.objectNumber= :objectNumber");
        q1.setParameter("objectNumber", objectNumber);
        Object1 obj1 = q1.getSingleResult();
        Query<Long> q2 = currentSession.createQuery("select count(id) from Object2 o where :object1param in elements(o.associatedObjects));
        q2.setParameter("object1param ", obj1);