I have a composite entity class as below in my Spring Data JDBC project which can be mapped to the table item
.
While fields id
, code
and itemName
are from table item
, field groupName
belongs to another table, item_group
.
I get this entity object successfully loaded by using a custom query in my repository as follows:
"SELECT a.id, a.code, a.name AS item_name, b.name as group_name from item a LEFT JOIN item_group b ON a.group_id = b.id where a.id=:id")
Is there any impact in having an @Id
annotated composite class like this?
public class Item
{
@Id
private long id;
private String code;
private String itemName;
private String groupName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
At first sight this does look off.
You won't be able to load, let alone save it using the standard CRUD methods.
It also looks wrong, because it looks like you are merging two aggregates: Item
and Group
, which really should be separate aggregates with no Java reference between them. See Spring Data JDBC, References, and Aggregates
But it does actually make sense if you consider it a view for specialised context. If you only need it for reading from the database it is quite a valid approach. It's simple and efficient, since it loads all required data in one select.
Assuming that is the situation you are in I would recommend the following:
@Query
annotation and just use the standard find...
methods.CrudRepository
but just Repository
and add manually only the methods you actually need. This avoids confusion and makes it obvious that this repository and therefore the entity must only be used for reading.find...
methods you must have a properly annotated id property. If you don't use the find...
methods, the @Id
annotation is superfluous.