500错误:无法获取数据,Hibernate属性访问异常求助
Hey there, let's tackle this 500 error you're facing head-on! The root cause is straightforward: Hibernate is trying to assign a null value to a primitive data type property (bse in FundsHolidayMaster), and primitive types like boolean, int, or long can't hold null values. Here are the most effective fixes:
1. Switch Primitive Type to Wrapper Class (Recommended)
This is the simplest and most widely used solution. Replace the primitive type with its corresponding wrapper class (which supports null values):
- For example, if your current code looks like this:
// Original primitive type (can't accept null) private boolean bse; public void setBse(boolean bse) { this.bse = bse; } - Update it to use the wrapper class:
// Wrapper class (can handle null) private Boolean bse; public void setBse(Boolean bse) { this.bse = bse; }
Wrapper classes (like Boolean, Integer, Long) natively support null, so Hibernate will no longer throw this exception when the database returns a null value for the bse column.
2. Enforce Non-Null Constraint with Default Value
If your business logic dictates that the bse field should never be null, you can:
- Modify your database table to set a default value for the
bsecolumn (e.g.,DEFAULT falsefor a boolean field) and mark it as non-nullable. - Update your entity class to reflect this constraint:
@Column(nullable = false, columnDefinition = "BOOLEAN DEFAULT false") private boolean bse;
This ensures the database never returns a null for the column, eliminating the root cause entirely.
3. Use Hibernate Custom Type Mapping (Special Cases)
If you must keep the primitive type for some reason, you can use Hibernate's @Type annotation to map null values to a default primitive value:
@Type(type = "org.hibernate.type.BooleanType") @Column(columnDefinition = "BOOLEAN") private boolean bse;
This will automatically convert null from the database to false (for boolean) or 0 (for numeric primitives). Note that this is less intuitive than using a wrapper class, so only use this if you have strict constraints preventing wrapper classes.
内容的提问来源于stack exchange,提问作者Sai Shashank

