When you use a view for querying, you often use the method of combining the primary key.
In Hibernate, a field that is configured in a combined primary key, if one of the values is NULL, hibernate sets the corresponding entity for the entire row to null.
Sometimes, it's not what we want.
The most likely solution on the web is to place a potentially null field outside of a composite primary key.
But in this case, the fields in the combined primary key may not be able to uniquely mark a record, so the result of the query is often not what we want.
For example: There is a view below
Year |
Faculties and Departments |
Name |
Number of awards |
2010 |
School of Computer Science |
Tom |
26 |
2010 |
School of Computer Science |
Null |
27 |
I would like to inquire about the number of awards given to a certain college teacher in a certain year, which uses a combined primary key, including years, faculties, and three fields of name.
If nothing is done, the corresponding entity in the second record of the result list returned using Hibernate is null, but if only the year is used as the Union primary key, then the two records cannot be distinguished.
we can do this:
Set a column ID when creating the view so that the value of the ID is a connection to the value in the combined primary key.
Create or replace view MyView as
Select v1. Year | | V1, Faculty and Department | | V1. Name as ID ... ....... ...... ..............
So the view above will become
Id |
Year |
Faculties and Departments |
Name |
Number of awards |
2010 Computer Institute John |
2010 |
School of Computer Science |
Tom |
26 |
2010 Computer Institute |
2010 |
School of Computer Science |
Null |
27 |
This way, when mapping in hibernate, you can map only one field ID as the primary key, and the primary key is generated as assigned, thus avoiding the use of the combined primary key, so that there is no problem with the combined primary key.
Of course this method requires that at least one of these three fields is not null.