Combining many-to-many associations and preventing cascades

So, we have a many-to-many relationship between the client and the role, configured as:

Customer {
  static hasMany = [roles: Role]
}

Role {
  static hasMany = [customer: Customer]
  static belongsTo = Customer
}

A Role object has only a name and a set of permissions. We do not want cascades to be saved using Customer → Role, since the role must be modified directly.

I added:

static mapping = {
  roles cascade: 'none'
}

but whenever I create a client, the role table is also updated. Nothing changes, except that the version number is incremented.

I am missing something else that needs to be installed ... is there a mistake in how many-to-many relationships and cascades are set in Grails ... or is there some other way to prevent roles from being updated every time?

+3
1

, , ( , ..). hasMany belongsTo CustomerRole

import org.apache.commons.lang.builder.HashCodeBuilder

class CustomerRole implements Serializable {

   Customer customer
   Role role

   boolean equals(other) {
      if (!(other instanceof CustomerRole)) {
         return false
      }

      other.customer?.id == customer?.id &&
         other.role?.id == role?.id
   }

   int hashCode() {
      def builder = new HashCodeBuilder()
      if (customer) builder.append(customer.id)
      if (role) builder.append(role.id)
      builder.toHashCode()
   }

   static CustomerRole get(long customerId, long roleId) {
      find 'from CustomerRole where customer.id=:customerId and role.id=:roleId',
         [customerId: customerId, roleId: roleId]
   }

   static CustomerRole create(Customer customer, Role role, boolean flush = false) {
      new CustomerRole(customer: customer, role: role).save(flush: flush, insert: true)
   }

   static boolean remove(Customer customer, Role role, boolean flush = false) {
      CustomerRole instance = CustomerRole.findByCustomerAndRole(customer, role)
      instance ? instance.delete(flush: flush) : false
   }

   static void removeAll(Customer customer) {
      executeUpdate 'DELETE FROM CustomerRole WHERE customer=:customer', [customer: customer]
   }

   static void removeAll(Role role) {
      executeUpdate 'DELETE FROM CustomerRole WHERE role=:role', [role: role]
   }

   static mapping = {
      id composite: ['customer', 'role']
      version false
      table 'customer_roles'
   }
}

DDL, , , - . , .

. hasMany, customer.addToRoles(...). CustomerRole, create , , remove.

class Role {
}

Customer

class Customer {
   Set<Role> getRoles() {
      CustomerRole.findAllByUser(this).collect { it.role } as Set
   }
}

getRoles(), roles, hasMany, .

+5

Source: https://habr.com/ru/post/1772878/


All Articles