I have a application_user
table with a corresponding UserEntity
record. Additionally, I have a user_meta_data
table with a UserMetaDataEntity
record as a 1:1 relation to the user
.
@Table("application_user")
record UserEntity(@Id @Nullable Long id,
// more columns
@Nullable
UserMetaDataEntity metaData
) {
// (...)
}
Currently, I need to directly write SQL queries, as I have some complex queries at hand that can't be modeled easily via function names. In these queries, I need to explicitly select all columns
@Query("""
SELECT application_user.ID AS ID, user_meta_data.phoneNumber AS USERMETADATA_PHONE_NUMBER
FROM application_user
INNER JOIN user_meta_data ON user_meta_data.user_id = application_user.id
""")
Stream<UserEntity> streamUsersWithMetaData();
But I want to avoid explicitly defining column names, as my actual entities have many columns. I would prefer calling SELECT * FROM application_user INNER JOIN ...
but this doesn't work, as Spring Data JDBC expects the column names to be prefixed with the joined table name.
Is there a way to define custom SQL queries without needing to define all columns in the SELECT statement?
CodePudding user response:
You can't use SELECT *
but there are at least two ways you can minimise the pain.
Either you define a static final String
containing the list of columns and concatenate them with the rest of the query.
Alternatively you can specify a RowMapper
doing the mapping. It could wrap the ResultSet
and forward the call to the original EntityRowMapper