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

时间:2018-12-26 03:56:08

标签: spring hibernate spring-mvc hql

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

我正在尝试编写一个查询,该查询将统计与特定customDetails=:myCriteria的{​​{1}}相关的EntitiesA中的EntityB

我已经使用id编写了必要的查询,该查询读取了session.CreateSQLQuery表,但是由于associated_entitites列已由休眠的customDetails加密,因此我无法使用它并返回@ColumnTransformer。而且我无法在HQL中复制它,因为BLOB未映射。

  

a

associated_entities
  

b

@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
}

2 个答案:

答案 0 :(得分:0)

我已经找到了解决方案,但是由于逻辑不是由休眠完成的,因此并不理想。必须在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;

答案 1 :(得分:0)

我发现的另一个解决方案是首选方法,因为它由冬眠执行,因为我发现它更快一些,它是使用两个单独的查询并利用{{1} }

下面的代码示例(不匹配问题示例,但应该清楚where :foo in elements()的想法和用法)

elements()