JPA issues - LiveStone/knowledge-base GitHub Wiki
- EntityGraph
EntityGraph<Order> graph = this.em.createEntityGraph(Order.class);
graph.addAttributeNodes("items");
Map<String, Object> hints = new HashMap<String, Object>();
hints.put("javax.persistence.loadgraph", graph);
this.em.find(Order.class, orderId, hints);
- JPA view entity (no id required)
@Immutable
@Entity
@Subselect("")
@Getter
@Setter
public class RequiredCourseUnitView {
public static final String REQUIRED_COURSE_UNITS = "REQUIRED_COURSE_UNITS";
@Column(name = "course_unit_id")
private String courseUnitId;
@EmbeddedId
private UnitRefView unit;
}
- Spring Data & Entity Graph to solve N+1 problem:
@Data
@Entity
@Table(name = "T_PARTICIPANT")
@NamedEntityGraphs({
@NamedEntityGraph(name="withRespondent", attributeNodes = {
@NamedAttributeNode("respondent")
})
})
public class Participant {
@Id
@Column(name = "ID_PARTICIPANT")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SQ_T_PARTICIPANT")
@SequenceGenerator(sequenceName = "SQ_T_PARTICIPANT", allocationSize = 1, name = "SQ_T_PARTICIPANT")
private long idParticipant;
@Column(name = "ID_OBSERVATION_RESULT_TYPE")
private long idObservationResultType;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_RESPONDENT", updatable = false, insertable = false)
private Respondent respondent;
@Column(name = "ID_RESPONDENT")
private long idRespondent;
@Column(name = "PERIOD")
private String period;
}
public interface ParticipantRepository extends CrudRepository<Participant, Long> {
@EntityGraph(value = "withRespondent", type = EntityGraph.EntityGraphType.LOAD)
List<ParticipantObservation> findAllByPeriod(String period);
List<ParticipantObservation> findByPeriod(String period);
}
Data jpa affords several prefixes (find, get, ...) for a method name. One possibility is to use different prefixes with different named graphs. Calling findAllByPeriod results in query:
select *
from t_participant participan0_ left outer join t_respondent respondent1_ on participan0_.id_respondent=respondent1_.id_respondent