将tinyint映射为布尔hibernate

我在MySQL表中有一个BOOLEAN类型(TINYINT(1)),我试图在实体中映射布尔字段,但这会产生exception:

org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: boolean 

我将我的实体中的字段更改为byte并进行相应的更改,使其作为布尔值,我得到:

 org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: tinyint 

我尝试在字段上使用@Type注释:

 @Type(type = "org.hibernate.type.NumericBooleanType") 

但我得到:

 org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: integer 

从我在这里读到:

org.hibernate.HibernateException:列管理员的maegul.users中的列类型错误。 找到:位,预期:整数

似乎Hibernate期待一个整数并得到一点。

这意味着您的注释现在是正确的:

 @Type(type = "org.hibernate.type.NumericBooleanType") 

但也许它已更新您的数据库以设置为Bit而不是整数,因此错误。

如果你真的需要TinyInt,你可以使用@Type AND @Column来设置TinyInt类型的Integer:

 @Column(columnDefinition = "TINYINT") @Type(type = "org.hibernate.type.NumericBooleanType") public boolean admin = true; 

更好地使用BIT(1)而不是TINYINT(1)

 @Column(nullable = false, columnDefinition = "BIT", length = 1) private boolean flag = false; 

尝试这个:

     

将它映射为int并使用访问器(isAdmin)获取布尔值有什么问题。 我希望你无论如何都会模糊实际的类型。

将其映射为org.hibernate.type.BooleanType可能有效。

请参阅http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/types.html#types-value-basic 。

我今天遇到了与hibernate类似的情况,最终将mysql数据类型作为tinyint(1)并将hibernate类型声明为boolean并且它完成了技巧

我能够通过在我的MySQL连接字符串中添加“transformedBitIsBoolean = true”来解决这个问题。

在Hibernate 4升级后看到这个问题: “发现:bit,expected:boolean”

这个论坛post: https : //hibernate.atlassian.net/browse/HHH-6935

@Type注释是用于JPA的hibernate注释,可以使用ColumnDefiniton属性。

 @Column(nullable = false, columnDefinition = "TINYINT(1)") private boolean isTrue; 

你可以从Dialect那里做到这一点,它不需要在所有地方进行繁琐的col级注释:

 import org.hibernate.Hibernate; 

import org.hibernate.dialect.PostgreSQLDialect;

import java.sql.Types;

公共类PostgresCustomConversionDialect扩展PostgreSQLDialect {

 public PostgresCustomConversionDialect() { super(); this.registerColumnType( Types.BIT, "numeric(1, 0)" ); this.registerColumnType( Types.BOOLEAN, "numeric(1, 0)" ); } public String toBooleanValueString(boolean bool) { return bool ? "1" : "0"; } 

}

然后使用这个自定义方言作为postgres方言 – “hibernate.dialect”