小编Joh*_*ann的帖子

将地图和属性列表保留为Grails中的JSON

编辑:onload()方法更改为afterLoad():否则对象可能无法正确传递给地图.


我目前正在使用一些具有大量动态,复杂属性的域类,我需要持续定期更新.

我将这些保存在每个类的Map结构中,因为这样可以很容易地在我的控制器等中进行引用.

但是,由于Grails似乎无法在DB中持久保存像List和Map这样的复杂属性类型,因此我使用以下方法通过JSON String对象实现此目的:

class ClassWithComplexProperties {

  Map complexMapStructure //not persisted
  String complexMapStructureAsJSON //updated and synched with map via onload,beforeInsert,beforeUpdate


  static transients = ['complexMapStructure']

  def afterLoad() {  //was previously (wrong!): def onLoad() {
    complexMapStructure=JSON.parse(complexMapStructureAsJSON)
  }
  def beforeInsert() {
    complexMapStructureAsJSON= complexMapStructure as JSON
  }
  def beforeUpdate() {
    complexMapStructureAsJSON= complexMapStructure as JSON
  }
  static constraints = {    
    complexMapStructureAsJSON( maxSize:20000)
  }
}
Run Code Online (Sandbox Code Playgroud)

这很好用,因为我只从数据库加载数据,但是当我想将我的更改保存到数据库时,我遇到了麻烦.例如,当我执行以下操作时

/* 1. Load the json String, e.g. complexMapStructureAsJSON="""{
   data1:[[1,2],[3,4]],//A complex structure of nested integer lists    
   data1:[[5,6]] //Another one
    }""" …
Run Code Online (Sandbox Code Playgroud)

grails persistence json grails-orm

14
推荐指数
1
解决办法
3123
查看次数

Grails瞬态属性未在对象创建时获取

从Grails 1.3.7迁移到2.0.4后,我注意到我的一个域类存在问题,我使用瞬态属性来处理密码.

我的域类看起来像这样(简化):

   package test

   class User {
String email 
String password1
String password2
//ShiroUser shiroUser

static constraints = {
    email(email:true, nullable:false, unique:true)
    password1(nullable:true,size:5..30, blank: false, validator: {password, obj ->

        if(password==null && !obj.properties['id']){
          return ['no.password']
        }
        else return true
      })
    password2(nullable:true, blank: false, validator: {password, obj ->
         def password1 = obj.properties['password1']

         if(password == null && !obj.properties['id']){
          return ['no.password']
        }
        else{
          password == password1 ? true : ['invalid.matching.passwords']
        }
      })

}
static transients = ['password1','password2']
   }
Run Code Online (Sandbox Code Playgroud)

在1.3.7中,这曾经在我的Bootstrap中工作:

    def user1= new User …
Run Code Online (Sandbox Code Playgroud)

grails grails-domain-class grails-2.0

12
推荐指数
1
解决办法
3879
查看次数