@ManyToOne到@MappedSuperclass中的实体将@ManyToOne的获取策略覆盖到子类中的同一实体

时间:2014-07-29 14:44:42

标签: hibernate spring-data-jpa

我最近在我们的Entity对象中添加了JPA审核。这是抽象类。

@MappedSuperclass
@JsonIgnoreProperties( { "createdBy", "lastModifiedBy", "createdDate", "lastModifiedDate" } )
public abstract class AbstractEntity<PK extends Serializable> implements Auditable<User, PK> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE )
    private PK id;

    @ManyToOne( fetch = FetchType.LAZY )
    private User createdBy;

    @Temporal( TemporalType.TIMESTAMP )
    private Date createdDate;

    @ManyToOne( fetch = FetchType.LAZY )
    private User lastModifiedBy;

    @Temporal( TemporalType.TIMESTAMP )
    private Date lastModifiedDate;

    //Getters and Setters from here

我已将User实体的关系设置为Lazy,以避免额外的查询,因为我们的应用程序代码中很少使用这些属性。

这是我的@Entity课程给我带来的麻烦:

@Entity
//So the outcomes property can be Lazy fetched in a Repository using an @EntityGraph
@NamedEntityGraph( name = "Participant.lazy" )
public class Participant extends AbstractEntity<Long> implements Serializable,     Identifiable<Long> {

    private static final long serialVersionUID = 1L;

    @ManyToOne( optional = false, fetch = FetchType.EAGER )
    @JoinColumn( name = "user_id" )
    private User user;

    @ManyToOne( optional = false, fetch = FetchType.LAZY )
    @JoinColumn( name = "event_id" )
    private Event event;

    @Column( nullable = false )
    private boolean virtual;

    @OneToMany( fetch = FetchType.EAGER, mappedBy = "participant" )
    @OrderBy( "id DESC" )
    private Set<ParticipantOutcome> outcomes;

    //Constructors, Getters, Setters, Equal and Hashcode from here

如果我删除AbstractEntity中的Auditable属性,则会急切地获取Participant.user。但是,如果我留在Auditable属性中Participant.user被强制为Lazy Fetch。

是否可以在同一@ManyToOne多个@Entity关系中使用不同的提取策略,还是必须删除AbstractEntity.createdByAbstractEntity.lastModifiedBy上的延迟提示?< / p>

1 个答案:

答案 0 :(得分:0)

我能想到的一种方法是要求切换到您要覆盖的属性的属性类型访问权限:

所以必须像这样改变AbstractEntity:

private User createdBy;

private User lastModifiedBy;

private Date lastModifiedDate;

@Access(AccessType.property) 
@ManyToOne( fetch = FetchType.LAZY )
public User getCreatedBy() {
    return createdBy;
}

@Access(AccessType.property) 
@ManyToOne( fetch = FetchType.LAZY )
public User getLastModifiedBy() {
    return lastModifiedBy;
}

参与者将覆盖这些方法:

@Access(AccessType.property) 
@ManyToOne( fetch = FetchType.EAGER)
public User getCreatedBy() {
    return createdBy;
}

@Access(AccessType.property) 
@ManyToOne( fetch = FetchType.EAGER)
public User getLastModifiedBy() {
    return lastModifiedBy;
}