0

I am attempting to re-use some code here. Say I have a base class:

@MappedSuperclass
@PersistenceUnit(name = "sample", unitName = "cools")
@IdClass(MyKey.class)
public class ParentEntity implements Serializable {

    @Id
    @Column(name = "my_id", nullable = false)
    private String id;

    @Id
    @Column(name = "name")
    private String name;

    // setters and getters
}

I then have these two children: ChildAEntity

@Entity
@Table(name = "Table_A", schema = "COOL_SCHEMA")
@NamedQuery(name = "getEverything.a", query = "select a from ChildAEntity a "
            + "where a.id=:id"),
    )
public class ChildAEntity extends ParentEntity implements Serializable {    
}

And ChildBEntity :

@Entity
@Table(name = "Table_B", schema = "COOL_SCHEMA")
@NamedQuery(name = "getEverything.b", query = "select a from ChildBEntity a "
            + "where a.id=:id"),
    )
public class ChildBEntity extends ParentEntity implements Serializable {    
}

My named queries are basically the same, except the table that they point to. ( As well as the named query name, but that is because they have to be distinct ).

Is it possible to make one named query that takes the entity as an argument? Looking at this post, it is possible to make a namedquery on a superclass. However, I am unsure as to how one would say "the class that extends me will be used as the entity" in the named query select statement.

Community
  • 1
  • 1
angryip
  • 2,140
  • 5
  • 33
  • 67
  • You could use the `TYPE` operator... or you could create the named queries dynamically at application startup using `EntityManagerFactory.addNamedQuery()`. – Nikos Paraskevopoulos Oct 27 '16 at 11:55
  • @NikosParaskevopoulos can you provide a sample of this TYPE operator you speak of? – angryip Oct 27 '16 at 12:36
  • It would be something like `SELECT x FROM ParentEntity x WHERE id=:id AND TYPE(x)=:type`, where you have to supply the id and the type ("ChildAEntity"/"ChildBEntity"), **BUT ONLY IF ParentEntity WAS AN ENTITY AND NOT A MAPPED SUPERCLASS**! Go for the `addNamedQuery` option, if you really need it. – Nikos Paraskevopoulos Oct 27 '16 at 13:02
  • ah i see. yea, that would not really work for me. The parent is not an entity, and if I am sharing functionality between classes, it should not be. thanks for the ideas tho. – angryip Oct 27 '16 at 14:31

0 Answers0