[Solution] An error occurred while querying some fields (including foreign keys) in Hibernate. a null pointer exception was reported. The hibernate Field
Assume that the current table structure is as follows:
The food table fields include foodid, name, foreign key businessid, and foreign key type.
Business table fields include: name and foreign key type.
Type table fields include id, name, and foodid.
The POJO generated by Hibernate is Food, Business, and Type.
You need to query some fields in the food table, such as name and foreign key businessid.
You can add a constructor with only the corresponding member variables to the Food class)
Use hql statements
select new Food(name,business) from Food where foodid=1
The above can be queried smoothly, but if you change the name and order
Use Food (Business business, String name)
Hql statement
select new Food(business, name) from Food where foodid=1
A null pointer exception is reported.
This is because the external key associated table Business also contains a field named name, so an error occurs. In this case, you only need to use an alias for the query table.
Correct statement:
select new Food(f.business, f.name) from Food f where foodid=1
Similarly, if the foreign key type is also queried, then:
Incorrect statement:
select new Food(name,business,type) from Food where foodid=1
Correct statement:
select new Food(f.name,f.business,f.type) from Food f where f.foodid=1