【问题标题】:JPA SubGraph to define fetchtype of an embedded propertyJPA SubGraph 定义嵌入属性的 fetchtype
【发布时间】:2015-02-17 14:04:37
【问题描述】:

我有一个实体Ride,它嵌入了一个可嵌入的“实体”RouteRoute 有一个 List 属性 towns 与 ManyToMany 关系,所以它有 fetchtype LAZY(我不想使用 EAGER)。所以我想为实体 Ride 定义一个 NamedEntityGraph,以加载带有 RouteRide 对象和实例化的城镇列表。 但是当我部署我的战争时,我得到了这个异常:

java.lang.IllegalArgumentException: 属性 [route] 不是托管类型

骑行

@Entity
@NamedQueries({
@NamedQuery(name = "Ride.findAll", query = "SELECT m FROM Ride m")})
@NamedEntityGraphs({
@NamedEntityGraph(
        name = "rideWithInstanciatedRoute",
        attributeNodes = {
            @NamedAttributeNode(value = "route", subgraph = "routeWithTowns")
        },
        subgraphs = {
            @NamedSubgraph(
                    name = "routeWithTowns",
                    attributeNodes = {
                        @NamedAttributeNode("towns")
                    }
            )
        }
    )
})
public class Ride implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Embedded
    private Route route;

    // some getter and setter
}

路线

@Embeddable
public class Route implements Serializable {
    private static final long serialVersionUID = 1L;

    @ManyToMany
    private List<Town> towns;

    // some getter and setter
}

【问题讨论】:

    标签: java jpa jpa-2.1 embeddable


    【解决方案1】:

    查看 Hibernate 对 org.hibernate.jpa.graph.internal.AttributeNodeImpl 的实现,我们得出结论,@NamedAttributeNode 不可能是:

    • 简单类型(Java 原语及其包装器、字符串、枚举、时态...)
    • 嵌入式(用@Embedded注释)
    • 元素集合(注解@ElementCollection
    if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC || 
        attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED ) {
        throw new IllegalArgumentException(
            String.format("Attribute [%s] is not of managed type", getAttributeName())
        );
    }
    

    我在 JPA 2.1 规范中没有发现类似的限制,因此这可能是 Hibernate 的缺点。


    在您的特定情况下,问题是 @NamedEntityGraph 指的是可嵌入的 Route 类,因此它在实体图中的使用似乎被 Hibernate 禁止(不幸的是)。

    为了使其正常工作,您需要稍微更改您的实体模型。我想到的几个例子:

    • Route 定义为实体

    • 移除Route并将其towns字段移动到Ride实体中(简化实体模型)

    • route字段从Ride移动到Town实体,将routedTowns的映射添加到Ride实体:

       @Entity
       public class Ride implements Serializable {
           ...
           @ManyToMany(mappedBy = "rides")
           private Map<Route, Town> routedTowns;
           ...
       }
      
       @Entity
       public class Town implements Serializable {
           ...
           @ManyToMany
           private List<Ride> rides;
           @Embeddable
           private Route route;
           ...
       }
      

    当然,实体图可能需要相应的更改。

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 2011-11-28
      • 2019-08-28
      • 2017-04-19
      • 2015-03-13
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多