简体   繁体   English

如何在自定义查询中加载@ElementCollection?

[英]How to load @ElementCollection within custom query?

I want to reduce the amount of querys run by spring. 我想减少Spring所运行的查询数量。 When getting an object with @ElementCollection via SQL I want to get the data for the ElementCollections directly via a JOIN within the quers. 通过SQL使用@ElementCollection获取对象时,我想直接通过查询中的JOIN获取ElementCollections的数据。

The attribute with the ElementCollection 具有ElementCollection的属性

@ElementCollection(fetch = FetchType.EAGER)
    @JoinTable(name = "song_genre_list")
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private List<String> genre;

The Method that uses a custom string: 使用自定义字符串的方法:

@Query(
    value = "select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1",
    nativeQuery = true)
List<Song> searchSong(String title);

How I would imagine defining a query that also loads this element collection: 我如何想象定义一个查询,该查询也加载此元素集合:

SELECT DISTINCT s.*, g.* FROM musicdb.songs s LEFT JOIN musicdb.song_genre_list g ON s.id = g.song_id WHERE s.name LIKE ?1 OR s.artist LIKE ?1

What Spring currently does (loading the genres for 3 songs with more querys): Spring目前正在做什么(加载带有更多查询的3首歌曲的流派):

Hibernate: select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?

What I want Spring to do: 我想要Spring做的事情:

Hibernate: select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1

The required Data for the ElementCollection is already included with the join. 连接中已包含ElementCollection所需的数据。 How can I tell spring to import that Data? 我如何告诉spring导入该数据?

FetchType.EAGER will already load the genres for you, so you dont need to write a join in your original query. FetchType.EAGER已经为您加载了类型,因此您无需在原始查询中编写联接。 But for that hibernate hibernate uses separate queries by default. 但是对于该休眠,默认情况下,休眠使用单独的查询。 To change this add the annotation '@Fetch(FetchMode.JOIN)' on the genre field 要更改此设置,请在体裁字段上添加注释“ @Fetch(FetchMode.JOIN)”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM