【问题标题】:Property reference Not found exception in springBoot MongoDB属性参考 SpringBoot MongoDB 中未发现异常
【发布时间】:2021-11-22 19:17:51
【问题描述】:

我声明了我想要存储在数据库中的所有内容,并且 提供数据类名称用户。所以不需要定义存储库 数据类中的内容详细信息。但是当我运行项目时,我得到了 运行时异常,属性引用未找到异常。

问题来了

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property existByUserName found for type User!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:92) ~[spring-data-commons-2.5.5.jar:2.5.5]
    at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:67) ~[spring-data-mongodb-3.2.5.jar:3.2.5]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:207) ~[spring-data-mongodb-3.2.5.jar:3.2.5]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.5.jar:2.5.5]
    ... 66 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:53978', transport: 

'套接字'

用户.kt

package com.nilmani.mychat.model

import org.jetbrains.annotations.NotNull
import org.springframework.data.mongodb.core.mapping.Document
import java.time.Instant
import java.time.LocalDate

@Document
data  class User(
    var id:String="",
    var userName:String="",
    var password:String="",
    var email:String="",
    var createdAt:LocalDate=LocalDate.now(),
    var updatedAt:LocalDate= LocalDate.now(),
    var active:Boolean=false,
    @NotNull
    var userProfile:Profile,
    @NotNull
    var role:Set<Role> = HashSet()
)

UserRepository.kt

package com.nilmani.mychat.repository

import com.nilmani.mychat.model.User
import org.springframework.data.mongodb.repository.MongoRepository
import java.util.*

interface UserRepository : MongoRepository<User,String> {
    fun findByUserName(userName:String):Optional<User>
     fun existByUserName(userName:String): Boolean
     fun existByEmail(email:String): Boolean
}

userService.kt

package com.nilmani.mychat.service

import com.nilmani.mychat.model.Role
import com.nilmani.mychat.model.User
import com.nilmani.mychat.repository.UserRepository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class UserService {
    val log : Logger = LoggerFactory.getLogger(UserService::class.java)
    @Autowired
    private lateinit var userRepository: UserRepository
    fun register(user:User,role:Role):User{
        log.info("Regestering user {}",user.userName)
        if (userRepository.existByUserName(user.userName)){
            log.warn("UserName already Exist", user.userName)
        }
        if(userRepository.existByEmail(user.email)){
            log.warn("This email already Registred",user.email)
        }
        user.active = true
        user.password = user.password
        user.role = user.role/**it auto automatically get the user type from role due to some conflict  set role provided by user*/
        return userRepository.save(user)
    }
}

UserAuthController.kt

package com.nilmani.mychat.controller

import com.nilmani.mychat.ezception.BadRequestException
import com.nilmani.mychat.ezception.EmailAlreadyExistException
import com.nilmani.mychat.ezception.UserNameAlreadyExistException
import com.nilmani.mychat.model.ApiResponse
import com.nilmani.mychat.model.Profile
import com.nilmani.mychat.model.Role
import com.nilmani.mychat.model.User
import com.nilmani.mychat.payload.Signup
import com.nilmani.mychat.service.UserService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.support.ServletUriComponentsBuilder
import java.net.URI


@RestController
class UserAuthController {
    @Autowired
    private lateinit var userService: UserService

    val log:Logger=LoggerFactory.getLogger(UserAuthController::class.java)
    @PostMapping(value = ["/users"], produces = [MediaType.APPLICATION_JSON_VALUE])
    fun createUser(@ModelAttribute request:Signup):ResponseEntity<*>{
        log.info("create User",request.username)
        val user:User = User(
            userName = request.username,
            email = request.email,
            password = request.password,
            userProfile = Profile(
                displayName = request.name,
                profilePictureUrl = request.profilePicUrl,
            )
        )
        try {
            userService.register(user, Role.USER)
        }catch (e:UserNameAlreadyExistException){
            throw BadRequestException(e.message)
        }catch (e:EmailAlreadyExistException){
            throw BadRequestException(e.message)
        }
        val location : URI = ServletUriComponentsBuilder
            .fromCurrentContextPath().path("users/{username}")
            .buildAndExpand(user.userName).toUri()
        return ResponseEntity
            .created(location)
            .body(ApiResponse(true,"User Registered successfully"))
    }
}

遇到此类问题的原因是什么,

【问题讨论】:

    标签: mongodb spring-boot kotlin


    【解决方案1】:

    这个问题是针对查询提出的,在用户存储库中定义。因为 springBoot 没有预定义查询existByUserName(userName:string), 在这种情况下,定义解决问题的自定义查询。

    类似这种类型的自定义查询

    UserRepository.kt

    package com.nilmani.mychat.repository
    
    import com.nilmani.mychat.model.User
    import org.springframework.data.mongodb.repository.MongoRepository
    import org.springframework.data.mongodb.repository.Query
    import org.springframework.transaction.annotation.Transactional
    import org.springframework.web.bind.annotation.RequestParam
    import java.util.*
    
    interface UserRepository : MongoRepository<User, String> {
        fun findByUserName(userName: String): Optional<User>
    
        @Transactional
        @Query("SELECT u from user WHERE u.userName =userName")
        fun existByUserName(@RequestParam("userName") userName: String): Boolean?
        @Transactional
        @Query("SELECT u from user WHERE u.email =email")
        fun existByEmail(@RequestParam("email") email: String): Boolean?
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-10
      • 2011-05-11
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      相关资源
      最近更新 更多