SpringBoot JPA Fetch / LoadGraph

时间:2016-09-07 19:49:25

标签: java jpa spring-boot eclipselink

我有两个实体

  'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'homestead'),
        'username'  => env('DB_USERNAME', 'homestead'),
        'password'  => env('DB_PASSWORD', 'secret'),
        'port'      => env('DB_PORT', 3306),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

@Entity
@Table(name = "LOCALIZATION")
@NamedQuery(name = "getByCountry,
    query = "SELECT ld FROM LocalizationDefinition ld WHERE ld.country = :country")
@NamedEntityGraph(name = "loadAll",
    attributeNodes = { @NamedAttributeNode(value = "localizations") })
public class LocalizationDefinition  {

  @Id
  @SequenceGenerator(name = "LocalizationSequence", sequenceName = "LOCALIZATION_SEQ", allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "LocalizationSequence")
private Integer id;

  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "localizationDefinition")
  private List<LocalizationEntry> localizations;
  ...
}

存储库提取

@Entity
@Table(name = "LOCALIZATION_DETAIL")
public class LocalizationEntry  {

  @Id
  @SequenceGenerator(name = "LocalizationDetailSequence", sequenceName = "LOCALIZATION_DETAIL_SEQ",
        allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "LocalizationDetailSequence")
  private Integer id;

  @ManyToOne 
  @JoinColumn(name = "LOCALIZATION_ID", nullable = false)
  private LocalizationDefinition localizationDefinition;
...
 }

我有一个自定义存储库实现,它使用命名查询和实体图来加载国家/地区的所有条目。我正在使用Spring Boot 1.4和嵌入式Tomcat,并尝试过EclipseLink 2.5.2和2.6.3。我的期望是,只创建了1个SQL查询但我最终遇到了n + 1查询问题。我确信这在一个月前在Weblogic Server 12c的JEE 7测试应用程序中按预期工作。

任何想法,如果我做错了什么或误解了什么?

完成persistence.xml 首先我是一个2.0版本,但将其更新为2.1并没有改变任何东西。

    public List<LocalizationDefinition> getByCountry(final String country) {
      final TypedQuery<LocalizationDefinition> query = em
            .createNamedQuery("getByCountry", LocalizationDefinition.class);

      query.setParameter("country", country);
      query.setHint("javax.persistence.loadgraph", em.getEntityGraph("loadAll"));

      final List<LocalizationDefinition> allLocalizations = query.getResultList();

      return allLocalizations;
 }

eclipselink.weaving在JPA配置类中设置为static。我还在pom.xml中的编译期间启用了静态编织。

设置query.setHint(QueryHints.FETCH,“ld.localizations”);在自定义存储库实现中解决了这个问题。但这是特定于提供者的,并且设置loadgraph应该已经完成​​了这项工作。

0 个答案:

没有答案