将tinyint映射为布尔值hibernate

Alv*_*ena 30 java mysql types hibernate

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

org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: boolean
Run Code Online (Sandbox Code Playgroud)

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

org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: tinyint
Run Code Online (Sandbox Code Playgroud)

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

@Type(type = "org.hibernate.type.NumericBooleanType")
Run Code Online (Sandbox Code Playgroud)

但我得到:

org.hibernate.HibernateException: Wrong column type in maegul.users for column admin. Found: bit, expected: integer
Run Code Online (Sandbox Code Playgroud)

Cyr*_* N. 37

从我在这里读到:

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

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

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

@Type(type = "org.hibernate.type.NumericBooleanType")
Run Code Online (Sandbox Code Playgroud)

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

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

@Column(columnDefinition = "TINYINT")
@Type(type = "org.hibernate.type.NumericBooleanType")
public boolean admin = true;
Run Code Online (Sandbox Code Playgroud)

  • 我问这个问题已经有一段时间了,这个问题相关的项目很久以前就已经丢失了.我真的不记得我是如何解决这个问题的,但是看到有些人发现这个答案是合适的,我会接受它. (3认同)

am0*_*0wa 7

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

@Column(nullable = false, columnDefinition = "BIT", length = 1)
private boolean flag = false;
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以从 Dialect 中完成,它不需要在所有地方进行繁琐的 col 级别注释:

import org.hibernate.Hibernate;
import org.hibernate.dialect.PostgreSQLDialect;
import java.sql.Types;

public class PostgresCustomConversionDialect extends 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";
    }

}
Run Code Online (Sandbox Code Playgroud)

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