使用 Hibernate 时如何在布尔属性中插入 null 值?
我有一个带有布尔属性的类。当我实例化并保留此类时,布尔属性将存储为“false”值,而不是预期的“null”。如何将布尔属性设置为“Null”?
I have a class with a Boolean attribute. When I instantiate and persist this class, the Boolean attribute is stored with the "false" value instead of the expectable "null". How can I set a Boolean attribute to "Null"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,确保您定义的是
Boolean
对象,而不是boolean
类型。然后,如果您将 Hibernate 与 JPA 属性一起使用,则可以添加 @Column(nullable=true) 来显式告诉 Hibernate 该列应将 NULL 作为默认值。
First, make sure that you define a
Boolean
object and not aboolean
type.Then, if you are using Hibernate with JPA attributes, then you can add
@Column(nullable=true)
to explicitly tell Hibernate the the column should have NULL as default.这是一个奇怪的问题。具有
null
值的Boolean
属性绝对应该存储为NULL
并且tinyint
列类型允许。我自己无法调查这个问题,但我会这样做:首先,我将激活 Hibernate 的 DML 语句和 JBDC 参数的日志记录,以确认 Hibernate 实际上正在传递 NULL(它应该)。相关类别(第 3.5日志记录)是
org.hibernate.SQL
和org.hibernate.type
。如果第一个测试没有揭示问题,我会尝试通过一个简单的测试类进一步隔离它,使用原始 JDBC 插入一个带有
null
值的Boolean
(并且也读一下)。如果这个测试不积极,那么我就会开始怀疑 JDBC 驱动程序。顺便问一下,您使用什么 JDBC 驱动程序(和版本)?如果您使用的是 Microsoft 驱动程序,请尝试使用最新版本的 jTDS(反之亦然)。
This is a weird problem. A
Boolean
attribute with anull
value is definitely supposed to be stored asNULL
and thetinyint
column type allows that. I cannot investigate the problem myself but here is what I would do:First, I would activate the logging of Hibernate's DML statements and of JBDC parameters to confirm that Hibernate is actually passing
NULL
(and it should). The relevant categories (chapter 3.5. Logging) areorg.hibernate.SQL
andorg.hibernate.type
.If the first test doesn't reveal the problem, I would try to isolate it further with a simple test class using raw JDBC to insert a
Boolean
with anull
value (and also read it). If this test is not positive, then I would start to suspect the JDBC driver.What JDBC driver (and version) are you using by the way? If you are using the Microsoft driver, try with the latest version of jTDS (and inversely).
首先,确保您尝试保留的对象是布尔值而不是原始布尔值。其次,您可以将对应的列定义为 char(1),它可以保存“Y”、“N”或 null 值。最后,最重要的是将以下行添加到 hibernate.cfg.xml 中:-
如果您使用 hibernate.properties 文件,则使用以下内容:-
这将帮助您将 null 值存储到布尔类型列。并且不要忘记在映射文件中将属性映射为 type="boolean"。
First you make sure that the object you are trying to persist is Boolean not primitive boolean. Secondly, you can define the column corresponding as char(1) which can hold 'Y', 'N' or null value. and lastly,and the most important add the following line to you hibernate.cfg.xml :-
if u are using hibernate.properties file then use following:-
this would help you out to store null values to boolean type column. and don't forget to map the property as type="boolean" in the mapping file.