简体   繁体   English

使用Hibernate时如何在布尔属性中插入空值?

[英]How do I insert the null value in a Boolean attribute when using Hibernate?

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". 当我实例化并持久化此类时,Boolean属性存储为“false”值而不是可预期的“null”。 How can I set a Boolean attribute to "Null"? 如何将布尔属性设置为“Null”?

First, make sure that you define a Boolean object and not a boolean type. 首先,确保定义一个Boolean对象而不是boolean类型。

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. 然后,如果您正在使用带有JPA属性的Hibernate,那么您可以添加@Column(nullable=true)以明确告诉Hibernate该列应该具有NULL作为默认值。

This is a weird problem. 这是一个奇怪的问题。 A Boolean attribute with a null value is definitely supposed to be stored as NULL and the tinyint column type allows that. 具有null值的Boolean属性绝对应该存储为NULL ,而tinyint列类型允许存储。 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). 首先,我将激活Hibernate的DML语句和JBDC参数的日志记录,以确认Hibernate实际上正在传递NULL (它应该)。 The relevant categories (chapter 3.5. Logging ) are org.hibernate.SQL and org.hibernate.type . 相关类别(第3.5。日志记录 )是org.hibernate.SQLorg.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 a null value (and also read it). 如果第一个测试没有揭示问题,我会尝试使用一个简单的测试类进一步隔离它,使用原始JDBC插入一个带null值的Boolean值(并且还读取它)。 If this test is not positive, then I would start to suspect the JDBC driver. 如果这个测试不是肯定的,那么我会开始怀疑JDBC驱动程序。

What JDBC driver (and version) are you using by the way? 你顺便使用什么JDBC驱动程序(和版本)? If you are using the Microsoft driver, try with the latest version of jTDS (and inversely). 如果您使用的是Microsoft驱动程序,请尝试使用最新版本的jTDS反之亦然 )。

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. 其次,您可以定义对应为char(1)的列,它可以保存'Y','N'或null值。 and lastly,and the most important add the following line to you hibernate.cfg.xml :- 最后,最重要的是在hibernate.cfg.xml中添加以下行: -

<property name="query.substitutions">'Y'=true,'N'=false</property>

if u are using hibernate.properties file then use following:- 如果您正在使用hibernate.properties文件,请使用以下内容: -

hibernate.query.substitutions true 'Y', false 'N'

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. 并且不要忘记在映射文件中将属性映射为type =“boolean”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM