[Solution] An error occurred while querying some fields (including foreign keys) in Hibernate. a null pointer exception was reported. The hibernate Field

Source: Internet
Author: User

[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

 

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.