开发者

Booleans in grails aren't persisted?

开发者 https://www.devze.com 2023-01-22 10:26 出处:网络
I\'m developing a small application on Grails 1.3.5 and I run into this very strange problem. My domain classes feature some boolean typed fields. None of these fields is persisted when creating a ne

I'm developing a small application on Grails 1.3.5 and I run into this very strange problem.

My domain classes feature some boolean typed fields. None of these fields is persisted when creating a new instance (and saving it of course).

For example, I have this domain class "Employee", defined as follows (simplified):

class Employee {
 String name
 boolean present
} 

When I create a new instance of that class and I persist it, the name is saved, but the present-named boolean isn't.

def newEmp = new Employee(name: "me", present: true)
newEmp.save(failOnError: true, flush: true)

When saving, no error is thrown. However, in the database (I use MySQL) the binary column "present" al开发者_开发问答ways remains empty.

What could be causing this? This happens alongs all my domain classes.


How are you querying the column? By 'empty' do you mean null? By default Hibernate + MySQL will persist booleans as a bit with value 0 or 1 so when running "select * from foo" the values look blank. You can cast to a number though:

select name, CAST(present AS UNSIGNED) from employee

Another thing you can do is use a custom Dialect that persists using a 'boolean' type instead of a bit:

package com.yourcompany.yourapp

import java.sql.Types
import org.hibernate.dialect.MySQL5InnoDBDialect

class MyDialect extends MySQL5InnoDBDialect {
   public MyDialect() {
      registerColumnType(Types.BIT, "boolean")
   }
}

Register this in DataSource.groovy as

dataSource {
   pooled = true
   driverClassName = 'com.mysql.jdbc.Driver'
   username = '...'
   password = '...'
   dialect = com.yourcompany.yourapp.MyDialect
}


Chances are the problem is somewhere else. I wrote an application in Grails 1.2 that use booleans and MySql and had no persistence issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消