[英]Hibernate and querying a view. Result count is OK, but all rows are the same but they aren't on the database
I have an entity representing a view on the (mysql) database:我有一个代表 (mysql) 数据库视图的实体:
@Entity
@Immutable
@Table(name = "user_info_view")
public class UserInfoView implements Serializable {
@Id
@Column(name = "user_uuid")
private String userUUID;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
//getters, setters, constructors...
}
The view is created using a simple SQL, like:该视图是使用简单的 SQL 创建的,例如:
CREATE OR REPLACE VIEW USER_INFO_VIEW
AS
SELECT u.USER_UUID,
u.NAME,
a.ADDRESS
FROM
USER u
JOIN
ADDRESS a
ON a.ID = u.ADDRESS_ID
And a repository:和一个存储库:
@Repository
public interface UserInfoViewRepository extends JpaRepository<UserInfoView, String> {
List<UserInfoView> findAllByUserUUID(String userUUID);
}
SELECT * FROM USER_INFO_VIEW
is returning 4 rows. SELECT * FROM USER_INFO_VIEW
返回 4 行。 Running findAllByUserUUID()
method returns a list of 4 UserInfoView
objects, but they are all the same - and they contain data from the first row in the database.运行
findAllByUserUUID()
方法返回 4 个UserInfoView
对象的列表,但它们都是相同的 - 它们包含来自数据库第一行的数据。
Here are the results of queries on the database:以下是对数据库的查询结果:
SELECT * FROM USER:从用户中选择 *:
id | user_uuid | name | address_id |
------------------------------------
1 | UUID1 | john | 1 |
2 | UUID1 | jane | 2 |
3 | UUID1 | josh | 3 |
4 | UUID1 | mark | 4 |
------------------------------------
SELECT * FROM ADDRESS:
id | address | name | is_current |
----------------------------------------------
1 | some address 1 | addr1 | 1 |
2 | some address 2 | addr2 | 0 |
3 | some address 3 | addr3 | 1 |
4 | some address 4 | addr4 | 1 |
----------------------------------------------
SELECT * FROM USER_VIEW WHERE USER_UUID = "UUID1":
user_uuid | name | address |
---------------------------------------
UUID1 | john | some address 1 |
UUID1 | jane | some address 2 |
UUID1 | josh | some address 3 |
UUID1 | mark | some address 4 |
---------------------------------------
What could be causing this behaviour?什么可能导致这种行为?
The fact that the user_uuid
column is not unique causes the duplicates since it's marked as @Id and JPA uses its value to find the entities. user_uuid
列不是唯一的这一事实会导致重复,因为它被标记为 @Id 并且 JPA 使用其值来查找实体。 You'll need a composite PK using either an IdClass
or an EmbeddedId
containing the identifiying attributes.您将需要使用包含标识属性的
IdClass
或EmbeddedId
的复合 PK 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.