已經過了一個星期,我正在努力解決一個問題,似乎我無法找到任何答案。多對多額外的列Spring JPA
Album
型號:
@Entity
@Table(name = DatabaseConstants.ALBUM_TABLE_NAME)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Album {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false)
private int imageVersion = 1;
@Column(length = 255)
private String description;
@Column(nullable = false)
private boolean single = false;
@Column(nullable = false)
private Long createdAt;
@Column(nullable = true)
private Long deletedAt;
// Relations
@OneToMany(fetch = FetchType.LAZY)
private List<AlbumView> albumViews;
// Getters and Setters
}
AlbumView
型號:
@Entity
@Table(name = DatabaseConstants.ALBUM_VIEW_RELATION_TABLE_NAME)
public class AlbumView {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private boolean bigger;
@Column(nullable = false)
private int position;
@Column(nullable = false)
private Long createdAt;
@Column(nullable = true)
private Long deletedAt;
// Relations
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "album_id")
private Album album;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "view_id")
private View view;
// Getters and Setters
}
View
型號:
@Entity
@Table(name = DatabaseConstants.VIEW_TABLE_NAME)
public class View {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Long createdAt;
@Column(nullable = true)
private Long deletedAt;
// Relations
@OneToMany(fetch = FetchType.LAZY)
private List<AlbumView> albumViewList;
// Getters and Setters
}
我需要通過視圖搜索相冊列表。我說,我需要查詢的是一樣的東西(從春天JPA使用@Query
註解):
SELECT a, av.bigger, av.position FROM Album a, AlbumView av WHERE av.view.id = ?
而是因爲他們沒有對Album
模型,我不能這兩個值(大,位置)映射。我需要建立像應對:
[
{
id: 1,
name: 'Test Album',
imageVersion: 1,
description: 'Description one',
single: true,
bigger: true,
position: 1
},
{
id: 2,
name: 'Test Album 2',
imageVersion: 1,
description: 'Description two',
single: true,
bigger: false,
position: 2
}
]
至於我讀,我不能用@Transient
幫我在這裏(因爲很明顯JPA忽略它和@Query
不填寫這些屬性)和我不不知道其他方式來做到這一點。 謝謝。
編輯1
我在Repository
類春天JPA的使用下面的代碼嘗試@bonifacio建議:
@Query("SELECT av.album.id, av.album.name, av.album.imageVersion, av.bigger, av.position FROM AlbumView av WHERE av.view.id = ?1")
List<AlbumView> findByViewId(Long id);
,但我得到了以下回應:
[
[
1,
"Test Best Hits",
1,
true,
1
]
]
值正是這樣,但它正在考慮這是一個數組,而不是像它假設的對象..
不能直接選擇AlbumView實體嗎? 'SELECT av.album.id,av。album.name,av.album.imageVersion,av.bigger,av.position FROM AlbumView av WHERE av.view.id =?'? – Bonifacio
@Bonifacio它有一種工作,但不完全,我更新了結果 – augustoccesar
@augustoccesar它的原因是因爲在我的例子和你的選擇什麼不是實體,而是一個數組,如果你選擇多個列的結果將始終是一個數組,這是默認的Hibernate的行爲。在這種情況下,你應該只選擇你想要的對象實體:'選擇av從相冊查看AV WHERE av.view.id =?1' – Bonifacio