How do I retrieve only the ID instead of the Entity of an association?

Viewed 9393

I have a class that looks something like this:

@Entity
public class EdgeInnovation {
    @Id
    public long id;
    @ManyToOne
    public NodeInnovation destination;
    @ManyToOne
    public NodeInnovation origin;
}

and another one that looks something like this:

@Entity
public class NodeInnovation {
    @Id
    public long id;
    @OneToOne
    public EdgeInnovation replacedEdge;
}

and so each table map to the other, so one entity will refer to other entities that will refer to more entities and so on, so that in the end there will be many entities that will be fetched from the database. Is there any way to only get the value (integer/long) of the key and not the entity it refers to? something like this:

@ManyToOne(referToThisTable="NodeInnovation")
@Entity
public class EdgeInnovation {
    @Id
    public long id;
    @ManyToOne(referToTable="NodeInnovation")
    public Long destination;
    @ManyToOne(referToTable="NodeInnovation")
    public Long origin;
}

and

@Entity
public class NodeInnovation {
    @Id
    public long id;
    @OneToOne(referToTable="EdgeInnovation")
    public Long replacedEdge;
}

Here's an example.

Here's an example. I want the stuff in green, I get all the stuff in red along with it. This wastes memory and time reading from disk.

4 Answers

I am aware I am quite late but some people might look for an answer to the same question - in your JPA repository you could do something like this:

@Query("SELECT new java.lang.Integer(model.id) FROM #{#entityName} model WHERE model.relationModeFieldlName.id IN :relationModelIds")
List<Integer> findIdByRelationModelIdIn(@Param("relationModelIds") List<Long> relationModelIds);
Related