2015-04-17 2 views
2

Я пишу заявку на Grails. Я пытаюсь добавить запись дочерней базы данных в родительскую таблицу с помощью метода addTo. Я следую документации this о методе addTo. И, например, документация говорит создать родительский класс:Grails - сохранить временный экземпляр перед промывкой

class Author { String name 
    static hasMany = [fiction: Book, nonFiction: Book] 
} 

Следуйте за этим я создал мой родитель-класс:

class Cafee { 

    String cafeeName = "" 
    int totalReservationPlaces = 0 
    double placeCost = 0 
    String currencyType = "" 
    boolean isReservationAvailable = false 
    boolean reservationTimeLimit = false 
    boolean reservationDateLimit = false 
    int totalPlaces = 0 
    long startTimeLimit = 0 
    long endTimeLimit = 0 
    Date startDateLimit = new Date() 
    Date endDateLimit = new Date() 

    static constraints = { 
     cafeeName blank: false, unique: true 
    } 

    String getCafeeName(){ 
     return cafeeName 
    } 

    static hasMany = [admin: Person] 
} 

Документация говорит создать дочерний-класс:

class Book { String title 
    static belongsTo = [author: Author] 
} 

Следуйте этим Я создал свой детский класс:

class Person { 

    transient springSecurityService 

    String username 
    String password 
    boolean enabled = true 
    boolean accountExpired 
    boolean accountLocked 
    boolean passwordExpired 

    String firstName 
    String lastName 
    String email 
    String inn = "" 
    boolean isAdminCafee = false 
    static transients = ['springSecurityService'] 

    static belongsTo = [cafee:Cafee] 

    static constraints = { 
     username blank: false, unique: true 
     firstName blank: false 
     lastName blank: false 
     password blank: false 
     email blank: false, unique: true 
    } 

    static mapping = { 
     password column: '`password`' 
    } 

    Set<Authority> getAuthorities() { 
     PersonAuthority.findAllByPerson(this).collect { it.authority } 
    } 

    def beforeInsert() { 
     encodePassword() 
    } 

    def beforeUpdate() { 
     if (isDirty('password')) { 
      encodePassword() 
     } 
    } 

    protected void encodePassword() { 
     password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password 
    } 
} 

И документация говорит, чтобы добавить запись ребенка к родителю, я должен сделать что-то это:

def fictBook = new Book(title: "IT") 
def nonFictBook = new Book(title: "On Writing: A Memoir of the Craft") 
def a = new Author(name: "Stephen King") 
      .addToFiction(fictBook) 
      .addToNonFiction(nonFictBook) 
      .save() 

Следуйте его в Bootstrap Я сделал это:

def user = Person.findOrSaveWhere(username: 'testerAndrewRes', password:'password', firstName:'Andrew', lastName:'Bobkov', email:'[email protected]', isAdminCafee: true, 
      inn: '1234567890') 
     println user 
     if(!user.authorities.contains(adminRole)) 
     { 
      PersonAuthority.create(user, adminRole, true) 
     } 
     def newCafe = new Cafee(cafeeName: "Tarelka").addToAdmin(user).save() 

Но я получаю сообщение об ошибке:

ERROR context.GrailsContextLoaderListener - Error initializing the application: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person 
Message: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person 

Что я делаю неправильно?

+0

PS. println user prints: restorator.auth.Person: (несохраненный). Зачем? Потому что findOrSaveWhere должно всегда ссылаться на сохраненный экземпляр. – pragmus

+1

http://stackoverflow.com/questions/13886331/grails-cant-add-child-record-to-parent как насчет того, чтобы вы протестировали его, выполнив addToAdmin, а затем новый Person .. как тест. С findOrSave вы не 't flush, так удивляйтесь, если есть какая-то другая логика, вызывающая вашу проблему, я бы сделал упрощенную проверку перед тем, как перейти к другим методам, а не к doc – Vahid

+0

Решенный, показать: [Grails, GORM, отношения. Необязательные дочерние записи] [1] [1]: http://stackoverflow.com/questions/29709158/grails-gorm-relationship-optional-child-records – pragmus

ответ

1

Сообщение об ошибке я думаю.
Попробуйте добавить:

user.save(flush:true) 

перед:

def newCafe = new Cafee(cafeeName: "Tarelka").addToAdmin(user).save() 
+1

Это Безразлично» t help – pragmus

+0

- такая же ошибка – dsharew

+0

да, ошибка такая же – pragmus

Смежные вопросы

 Смежные вопросы