Kevin Andrid
Kevin Andrid

Reputation: 1961

Join query for any type mapping on Hibernate

I've Implemented Any relationship Tag entity mapping with Asset,Patient,Staff

I tried below JPQL Query

em.createQuery("select t from Tag t join t.tagAssociation ta");

I got the following error

org.hibernate.hql.internal.ast.QuerySyntaxException: An AnyType attribute cannot be join fetched error

What is wrong with the query ? How to write join query and I want to fetch Asset and Tag associated list.

Code:

 public interface ITagAssociatable {
 public String getName();   
}

 @Entity
 public class Tag {
 @Id
 private String tagSerialNumber;    

@JsonIgnore
@Any(metaColumn = @Column(name = "tag_association_type"))
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
        @MetaValue(targetEntity = Asset.class, value = "Asset"),
        @MetaValue(targetEntity = Staff .class, value = "Staff"),
        @MetaValue(targetEntity = Patient.class, value = "Patient") })
@Cascade({ org.hibernate.annotations.CascadeType.MERGE })
@JoinColumn(name = "tag_association_id")
private ITagAssociatable tagAssociation;
 }

    @Entity
    public class Asset implements ITagAssociatable {
@Id
private Long id;
private String name
  }

    @Entity
    public class Staff implements ITagAssociatable {
@Id
private Long id;
private String name;
  }

    @Entity
    public class Patient implements ITagAssociatable{
@Id
private Long id;
private String name
  }

Upvotes: 0

Views: 554

Answers (1)

ewramner
ewramner

Reputation: 6233

I can't find where it is specifically forbidden (so perhaps someone else can provide a better answer?), but the documentation warns that it is impossible to create foreign keys for this type of relation and an eager join would be quite complex. Most likely Hibernate doesn't support join fetch for @Any and will read the relations with separate selects later instead. If so you can use @BatchSize to read many relations with one select, avoiding the N+1 problem.

Upvotes: 1

Related Questions