Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

hibernate - Restrict Database Query to Single Entity

I have below entity classes:

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Entity1 {

//other variables

@Id
@Column(name="ID")
private String id;

@OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL,
            mappedBy = "entity1")
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private Entity2 entity2;

}
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Entity2 {

//other variables

@Id
@Column(name = "ID", unique = true, nullable = false)
private String id;

@OneToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "ID")
    @MapsId
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private Entity1 entity1;

}

I am using Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable); from JpaSpecificationExecutor<T> interface to query the database.

Now I want to fetch data only from table associated with Entity1 and not from Entity2. But findAll() is fetching data from both the tables. Also I do not want to use @Query.

Can anyone please suggest how I can update my code to fetch data only from Entity1 table given that I need to store and update the data on both tables using save() method.

Let me know if any more details are required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You use bidirectional @OneToOne association. So, as it suggested in the documentation:

Although you might annotate the parent-side association to be fetched lazily, Hibernate cannot honor this request since it cannot know whether the association is null or not.

The only way to figure out whether there is an associated record on the child side is to fetch the child association using a secondary query. Because this can lead to N+1 query issues, it’s much more efficient to use unidirectional @OneToOne associations with the @MapsId annotation in place.

However, if you really need to use a bidirectional association and want to make sure that this is always going to be fetched lazily, then you need to enable lazy state initialization bytecode enhancement and use the @LazyToOne annotation as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...