无法在一对一关系中更新所属方的属性



我有一个User类,每个用户实例都有一个概要文件。个人资料有一个avatarImage属性,我想更新它。我可以在运行时更新用户的字段,但不能更新该用户的配置文件的字段。我正在使用springsecurity获取currentUser,我想更新他的avatarImage,但在运行时收到了SQLException。

用户域类别:

package com.clinton.kiitsocial
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {
private static final long serialVersionUID = 1
transient springSecurityService
//don't touch this...for spring-security
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
//starting custom domain...can touch this
Integer uniqueId
Date dateCreated
Date lastUpdated
static hasMany = [contents: Content]
static hasOne = [profile: Profile]

User(String username, String password) {
this()
this.username = username
this.password = password
}
Set<Role> getAuthorities() {
UserRole.findAllByUser(this)*.role
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
static transients = ['springSecurityService']
static constraints = {
username blank: false, unique: true
password blank: false, minSize: 5, validator: { pass, user ->
pass != user.username
}
uniqueId blank: false, unique: true, range: 1000..2000000000
profile unique: true, nullable: true
contents nullable: true
}
static mapping = {
password column: '`password`'
profile fetch: 'join'
}

}

配置文件域类别:

package com.clinton.kiitsocial
class Profile {
String bio
String contact
String address
GenderList gender
String emailId
Avatar avatarImage
User user
static hasMany = [socialNetworks: Social]
static constraints = {
bio nullable: true, maxSize: 50
address nullable: true, maxSize: 50
contact nullable: true, matches: "^\+(?:[0-9] ?){6,14}[0-9]$"
socialNetworks nullable: true, unique: true
gender nullable: true, blank: false
emailId email: true, blank: true
avatarImage nullable: true
}
}

用户控制器:

@Secured(['ROLE_ADMIN', 'ROLE_USER'])
class UserController extends RestfulController {
static responseFormats = ['json', 'xml']
def userService
UserController() {
super(User)
}
def uploadAvatar() {
MultipartFile avatar = request.getFile('avatar')
avatar ? respond (userService.uploadingAvatar(avatar)): respond (500)
}
def showAvatar() {
}
}

用户服务:

package com.clinton.kiitsocial
import grails.plugin.springsecurity.SpringSecurityService
import grails.transaction.Transactional
import org.springframework.web.multipart.MultipartFile
@Transactional
class UserService {
SpringSecurityService springSecurityService
private static final acceptedAvatarTypes = ['image/png', 'image/jpeg', 'image/gif']
User uploadingAvatar(MultipartFile file) {
User user = (User) springSecurityService.currentUser
Profile profile = Profile.findOrSaveByUser(user)
assert profile.user.username == user.username
//assert !profile.avatarImage
String message = ""
if (!acceptedAvatarTypes.contains(file.contentType)) {
//message = "Avatar must be one of: ${acceptedAvatarTypes} type"
//respond 500
return user
}
profile.avatarImage = new Avatar(avatar: file.bytes, avatarType: file.contentType)
println("uploading: ${profile.avatarImage.avatarType}")
if (!profile.save(failOnError: true, flush: true)) { //Error ocurs here
message = "error occurred saving image"
println("${profile.errors}")
//respond user.errors
return user
}
message = "Avatar (${profile.avatarImage.avatarType}, ${profile.avatarImage.avatar.size()} bytes) uploaded."
println(message)
println("finishing...")
return user
}
/*def showAvatar(long  userId) {
def avatarUser = User.get(userId)
if (!avatarUser || !avatarUser.profile.avatarImage || !avatarUser.profile.avatarType) {
//respond 404
return
}
response.contentType = avatarUser.profile.avatarType
response.contentLength = avatarUser.profile.avatarImage.size()
OutputStream out = response.outputStream
out.write(avatarUser.profile.avatarImage)
out.close()
}*/
}

错误/堆栈跟踪:

上传:image/png 2016-12-17 12:27:48.668错误---[nio-8080-exec-9]o.h.engine.jdbc.spi.SqlExceptionHelper:参数未设置"#1";SQL语句:选择this_.id作为id1_3_0_,this_版本为版本2_3_0_,this_地址为地址3_3_0_,this_avatar_image_id为avatar_i4_3_0_、this_.bio为bio5_3_0_,this_contact为contact6_3_0_,this_email_id为email_id7__3_0_,this_.gender为gender8_3_0_,this_.user_id为user_id9_3_0_来自配置this_where this_.id=?【90012-192】2016-12-17 12:27:48.711错误---[nio-8080-exec-9]o.g.web.errors.GrailsException解析程序:处理请求时发生JdbcSQLException:[POST]/api/avatars参数"#1"未设置;SQL语句:选择this_.id作为id1_3_0_,this_版本为版本2_3_0_,this_地址为地址3_3_0_,this_avatar_image_id为avatar_i4_3_0_、this_.bio为bio5_3_0_,this_contact为contact6_3_0_,this_email_id为email_id7__3_0_,this_.gender为gender8_3_0_,this_.user_id为user_id9_3_0_来自配置this_where this_.id=?【90012-192】。Stacktrace如下:

java.lang.reflect.InvocationTargetException:null位于org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsCoontrollerClass.java:210)位于org.grails.core.DefaultGrailsControllerClass.ioke(DefaultGrailsCoontrollerClass.java:187)网址:org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsIInfoHandlerAdaper.groovy:90)网址:org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)位于org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)网址:org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java)网址:org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)网址:org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)网址:org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)位于grails.plugin.springsecurity.rest.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.groovy:143)位于grails.plugin.springsecurity.rest.RestLogoutFilter.doFilter(RestLogoutFilter.groovy:80)位于grails.plugin.springsecurity.rest.RestTokenValidationFilter.processFilterChain(RestTokenValidatationFilter.groovy:118)位于grails.plugin.springsecurity.rest.RestTokenValidationFilter.doFilter(RestTokenValidatationFilter.groovy:84)网址:org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)网址:org.springframework.security.web.access.eccept.FilterSecurityInterceptor.ioke(FilterSecurityIntercepter.java:127)网址:org.springframework.security.web.access.eccept.FilterSecurityInterceptor.doFilter(FilterSecurityIntercepter.java:91)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)网址:org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)位于grails.plugin.springsecurity.rest.RestTokenValidationFilter.processFilterChain(RestTokenValidatationFilter.groovy:118)位于grails.plugin.springsecurity.rest.RestTokenValidationFilter.doFilter(RestTokenValidatationFilter.groovy:84)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)网址:org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAware RequestFilter.java:169)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)位于grails.plugin.springsecurity.rest.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.groovy:143)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)在grails.plugin.springsecurity.web.authentication.loogout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)位于grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderCilter.groovy:58)网址:org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)网址:org.springframework.security.web.FilterChainPoxy.doFilterInternal(FilterChainProxy.java:214)网址:org.springframework.security.web.FilterChainPoxy.doFilter(FilterChainProxy.java:177)网址:org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequest Filter.java:77)网址:org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)位于java.util.concurrent.ThreadPoolExecutiator.runWorker(ThreadPoolExecutiator.java:1142)位于java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)在java.lang.Thread.run(Thread.java:745)由以下原因引起:org.springframework.jdbc.UncategorizedSQLException:Hibernate操作:无法提取ResultSet;的未分类SQLExceptionSQL[n/a];SQL状态【90012】;错误代码【90012】;参数"#1"为未设置;SQL语句:选择this_.id作为id1_3_0_,选择this_.version作为版本2_3_0_,this_.address为地址3_3_0_、this_.avatar_image_id作为avatar_i4_3_0_,this_.bio作为bio5_3_0_;this_contact作为contact6_3_0_,this_.email_id为email_id7__3_0_;this_.gender为gender8_3_0_,this_.user_id作为配置文件this_中的user_id9_3_0_this_.id=?【90012-192】;嵌套异常为org.h2.jdbc.JdbcSQLException:未设置参数"#1";SQL语句:选择this_.id作为id1_3_0_,选择this_.version作为版本2_3_0_,this_.address为地址3_3_0_、this_.avatar_image_id作为avatar_i4_3_0_,this_.bio作为bio5_3_0_;this_contact作为contact6_3_0_,this_.email_id为email_id7__3_0_;this_.gender为gender8_3_0_,this_.user_id作为配置文件this_中的user_id9_3_0_this_.id=?【90012-192】网址:org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate网址:org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate网址:org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate位于org.grails.orm.hhibernate。GrailsHibernate Template.covertJdbcAccessException(Grailshibernate Template.java:668)位于org.grails.orm.hhibernate。GrailsHibernate模板。convertHibernate访问异常(Grailshibernate模板。java:656)位于org.grails.orm.hhibernate。GrailsHibernate Template.doExecute(Grailshibernate Template.java:247)网址:org.grails.orm.hhibernate。GrailsHibernate Template.exexecute(Grailshibernate Template.java:187)位于org.grails.orm.hhibernate。GrailsHibernate Template.exexecute(Grailshibernate Template.java:110)网址:org.grails.orm.hhibernate.validation.UniqueConstraint.processValidate(UniqueConstraint.java:149)grails.validation.AbstractConstraint.validate(AbstractConstraint.java:107)在grails.validation.ConstrainedProperty.validate(ConstraintdProperty.java:979)位于org.grails.validation.GrailsDomainClassValidator.validatePropertyWithConstraint(GrailsDomainClassValidator.java:211)网址:org.grails.validation.GrailsDomainClassValidator.validate(GrailsDomainClassValidator.java:81)位于org.grails.orm.hhibernate。AbstractHibernate GormInstanceApi.save(Abstracthibernate GormInstance Api.groovy:122)位于org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:151)网址:com.clinton.kiitsocial.UserService$$EQ5cdaRc.$tt__uploadingAvatar(UserService.groovy:26)位于grails.transaction.GrailsTransactionTemplate$2.doInTransaction(GrailsTransaction Template.groovy:96)网址:org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)位于grails.transaction.GrailsTransactionTemplate.exexecute(GrailsTransaction Template.groovy:93)网址:com.clinton.kiitsocial.UserController$$EQ5ccaGm.uploadAvatar(UserController.groovy:20)…省略了38个常见帧,原因是:org.h2.jdbc.JdbcSQLException:未设置参数"#1";SQL语句:选择this_.id作为id1_3_0_,选择this_.version作为版本2_3_0_,this_.address为地址3_3_0_、this_.avatar_image_id作为avatar_i4_3_0_,this_.bio作为bio5_3_0_;this_contact作为contact6_3_0_,this_.email_id为email_id7__3_0_;this_.gender为gender8_3_0_,this_.user_id作为配置文件this_中的user_id9_3_0_this_.id=?【90012-192】位于org.h2.message.DbException.getJdbcSQLException(DbException.java:345)网址:org.h2.message.DbException.get(DbException.java:179)位于org.h2.message.DbException.get(DbException.java:155)网址:org.h2.expression.Parameter.checkSet(Parameter.java:81)网址:org.h2.command.Prepared.checkParameters(Prepared.java:164)网址:org.h2.command.CommandContainer.query(CommandContainer.java:109)在org.h2.command.command.executeQuery(command.java:201)网址:org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcpreparedStatements.java:110)位于org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)在org.hibernate.loader.loader.getResultSet(loader.java:2122)在org.hibernate.loader.loader.executeQueryStatement(loader.java:1905)在org.hibernate.loader.loader.executeQueryStatement(loader.java:1881)在org.hibernate.loader.loader.doQuery(loader.java:925)位于org.hibernate.loader.loader.doQueryAndInitializeNonLazyCollection(loader.java:342)在org.hibernate.loader.loader.doList(loader.java:2622)在org.hibernate.loader.loader.doList(loader.java:2605)位于org.hibernate.loader.loader.listIgnoreQueryCache(loader.java:2434)在org.hibernate.loader.loader.list(loader.java:2429)网址:org.hibernate.loader.criteria.criteria.loader.list(criteria loader.java:109)位于org.hibernate.internal.SessionImpl.list(SessionImpl.java:1787)网址:org.hibernate.internal/CriteriaImpl.list(CriteriaImpl.java:363)网址:org.grails.orm.hhibernate.validation.UniqueConstraint$2.call(UniqueConstraint.java:210)网址:org.grails.orm.hhibernate.validation.UniqueConstraint$2.call(UniqueConstraint.java:149)位于org.grails.orm.hhibernate。GrailsHibernate Template.doExecute(Grailshibernate Template.java:243)…52个普通帧省略

我花了两天时间试图解决这个问题。欢迎所有建议。谢谢你抽出时间。。

我想明白了。我对它进行了集成测试,并认为:hibernate需要在将内部域附加到父域之前对其进行持久化和刷新。就像自下而上的时尚。请参阅下面的答案。它是由瞬态域实例引起的。

Avatar uploadingAvatar(MultipartFile file) {
User user = (User) springSecurityService.currentUser
if (!user.profile) user.profile = new Profile(user: user).save(flush: true)
if (!acceptedAvatarTypes.contains(file.contentType)) {
responseCode = 500
}
Avatar avatar = user.profile.avatarImage ?: new Avatar()
avatar.avatarName = file.originalFilename
avatar.avatarBytes = file.bytes
avatar.avatarType = file.contentType
if (!avatar.validate() && !avatar.save(flush: true)){
responseCode = 500
return avatar
}
user.profile.avatarImage = avatar
println("Avatar changed success")
responseCode = 200
return avatar
}

最新更新