Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

java - Hibernate JPA, MySQL and TinyInt(1) for Boolean instead of bit or char

Here is my JPA2 / Hibernate definition:

Code:
@Column(nullable = false)
private boolean enabled;

In MySql this column is resolved to a bit(1) datatype - which does not work for me. For legacy issues I need to map the boolean to a tinyint not to a bit. But I do not see a possibility to change the default datatype. Is there any?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@Type annotation is an Hibernate annotation.

In full JPA2 (with Hibernate 3.6+), the way to map a Boolean field to a TINYINT(1) SQL type instead of BIT(1), is to use the columnDefinition attribute.

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

nb: length attribute seems to have no effect in this case, then we use (1) syntax.


With Hibernate 4.0+, this kind of syntax can cause an runtime error like this :

Wrong column type Found: bit, expected: TINYINT(1)

It seems that in this case, your only way is to use tinyInt1isBit=false in the MySQL datasource connection string like this :

jdbc:mysql://server_host:3306/database?tinyInt1isBit=false

By the way, you can now use the length attribute like this :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...