我正在尝试将收费对象保存到集合中,该集合是嵌入式对象。更新功能正在按预期方式工作。问题是当我也更新密码更新时。
我正在使用grails spring安全插件。它具有用于编码密码的类。 UserPasswordEncoderListener
使用grails 3.3.8,gorm 6.1.10.RELEASE和mongodb。
这是我尝试更新收藏集的方式:
def user = User.findByUsername("username")
def charge = new Charge(
amount: "100",
description: "some description",
user: user
)
def customer = new Customer(
charges: [charge]
)
user.customer = customer
user.save flush: true, failOnError:true
有什么主意吗?或保存/更新嵌入式对象的最佳选择是什么? 该文档介绍了一些方法https://docs.grails.org/latest/ref/Domain%20Classes/addTo.html
我尝试没有成功。
用户类别
@GrailsCompileStatic
@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {
/* MongoDB */
ObjectId id
...
String username
String password
/* Role Users */
Set<Role> authorities
Customer customer
static embedded = ['authorities', 'customer']
static mapping = {
collection "users"
password column: '`password`'
}
...
}
客户分类
@GrailsCompileStatic
class Customer implements Serializable {
...
static hasMany = [
charges: Charge
]
...
}
收费舱
@GrailsCompileStatic
class Charge implements Serializable {
ObjectId id
String amount
static belongsTo = [ user: User ]
static mapping = {
collection "charges"
}
...
}
UserPasswordEncoderListener类
@Override
protected void onPersistenceEvent(AbstractPersistenceEvent event) {
if (event.entityObject instanceof User) {
User u = (event.entityObject as User)
if (u.password && (event.eventType == EventType.PreInsert || (event.eventType == EventType.PreUpdate && u.isDirty('password')))) {
event.getEntityAccess().setProperty("password", encodePassword(u.password))
}
}
}