带注释的hibernate映射id/long外键到可空列

duc*_*cin 2 java null annotations hibernate foreign-keys

我有以下类映射MySQL表:

@Entity
@Table(name = "category")
public class Category {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "parent_id")
    private long parentId;
Run Code Online (Sandbox Code Playgroud)

当处理具有NULL值的parent_id列的列时,我收到以下错误:

INFO: HHH000327: Error performing load command : org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.blogspot.symfonyworld.wealthylaughingduck.model.Category.parentId

这只是一个java错误:无法将NULL赋给longtype(private long parentId).我找不到任何暗示如何克服这个问题,我只能想到的替换longLong.这是一个好主意,还是有一些内置的hibernate注释或任何机制来完成这个特定的东西?

Per*_*ion 6

您将类属性定义为基元(long),但数据库表包含相应列的空值.提供程序(Hibernate)不会将null映射到基元,因为映射是不明确的.

如果您的数据可能包含空值,则需要使用等效的包装类(在本例中为Long).

@Entity
@Table(name = "category")
public class Category {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "parent_id")
    private Long parentId;
}
Run Code Online (Sandbox Code Playgroud)