首页 > 解决方案 > 找不到实体数据类型的属性

问题描述

为什么这个错误多次发生我不明白这个错误的主要问题或原因是什么。下面我的代码有什么问题吗?我定义了所有内容

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property categoryId found for type Product! Did you mean 'category_id'?
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.4.jar:2.5.4]Caused by: org.springframework.data.mapping.PropertyReferenceException: No property categoryId found for type Product! Did you mean 'category_id'?
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.4.jar:2.5.4]

产品.kt

package com.example.cms.entity

import org.hibernate.annotations.UpdateTimestamp
import java.time.LocalDateTime
import javax.persistence.*
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size

@Entity
data class Product(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id:Int=0,
    @Size(min = 4,message = "Name must be 4 and above ")
    val name:String="",
    var slug:String="",
    @Size(min = 5,message = "Name must be 5 and above ")
    val description:String="",
    var image:String="",
    @Pattern(regexp = "^[0-9]+([.][0-9]{1,2})?", message = "Expected format: 5, 5.99, 15, 15.99")
    val price:String="",
    @Pattern(regexp = "^[1-9][0-9]*", message = "Please choose a category")
    @Column(name = "category_id",nullable = false)
    val category_id:String="",
    @Column(name = "created_at")
    @UpdateTimestamp
    val createdAt:LocalDateTime=LocalDateTime.now(),
    @Column(name = "updated_at")
    @UpdateTimestamp
    val updatedAt:LocalDateTime=LocalDateTime.now()

)

ProductRepository.kt

package com.example.cms.repository

import com.example.cms.entity.Product
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository

interface ProductRepository:JpaRepository<Product,Int> {
    fun findBySlug(slug: String): Product

    fun findBySlugAndIdNot(slug: String, id: Int): Product
    fun allpages(pageable: Pageable):Page<Product>
    fun findAllByCategoryId(category_id: String?, pageable: Pageable?): List<Product?>?
    fun countByCategoryId(category_id: String?): Long

}

AdminProductController.kt

package com.example.cms.controller

import com.example.cms.entity.Category
import com.example.cms.entity.Product
import com.example.cms.repository.CategoryRepository
import com.example.cms.repository.ProductRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import javax.validation.Valid
import kotlin.math.ceil

@Controller
@RequestMapping("/admin/products")
class AdminProductController {
    @Autowired
    private lateinit var productRepository: ProductRepository
    @Autowired
    private lateinit var categoryRepository: CategoryRepository

    @GetMapping
    fun index(model: Model, @RequestParam(value = "page", required = false) p: Int): String {
        val perPage = 6
        val page = p ?: 0
        val pageable: Pageable = PageRequest.of(page, perPage)
        val product: Page<Product> = productRepository.allpages(pageable)
        val categories: List<Category> = categoryRepository.findAll()
        val cats = HashMap<Int, String>()
        for (cat in categories) {
            cats[cat.id] = cat.name
        }
        model.addAttribute("product", product)
        model.addAttribute("cats", cats)
        val count: Long = productRepository.count()
        val pageCount = ceil(count.toDouble() / perPage.toDouble())
        model.addAttribute("pageCount", pageCount.toLong())
        model.addAttribute("perPage", perPage)
        model.addAttribute("count", count)
        model.addAttribute("page", page)
        return "/resources/templates/admin/products/index.html"
    }
    @GetMapping("/add")
    fun add(product: Product?, model: Model): String? {
        val categories: List<Category> = categoryRepository.findAll()
        model.addAttribute("categories", categories)
        return "resources/admin/products/add.html"
    }
    @PostMapping("/add")
    @Throws(IOException::class)
    fun add(
        @Valid
        product:Product,
        bindingResult: BindingResult,
        file: MultipartFile,
        redirectAttributes: RedirectAttributes,
        model: Model
    ): String? {
        val categories: List<Category> = categoryRepository.findAll()
        if (bindingResult.hasErrors()) {
            model.addAttribute("categories", categories)
            return "resources/admin/products/add.html"
        }
        var fileOK = false
        val bytes = file.bytes
        val filename = file.originalFilename
        val path = Paths.get("src/main/resources/static/media/$filename")
        if (filename!!.endsWith("jpg") || filename.endsWith("png")) {
            fileOK = true
        }
        redirectAttributes.addFlashAttribute("message", "Product added")
        redirectAttributes.addFlashAttribute("alertClass", "alert-success")
        val slug: String = product.name.toLowerCase().replace(" ", "-")
        val productExists: Product = productRepository.findBySlug(slug)
        if (!fileOK) {
            redirectAttributes.addFlashAttribute("message", "Image must be a jpg or a png")
            redirectAttributes.addFlashAttribute("alertClass", "alert-danger")
            redirectAttributes.addFlashAttribute("product", product)
        } else if (productExists != null) {
            redirectAttributes.addFlashAttribute("message", "Product exists, choose another")
            redirectAttributes.addFlashAttribute("alertClass", "alert-danger")
            redirectAttributes.addFlashAttribute("product", product)
        } else {
            product.slug=slug
            product.image=filename
            productRepository.save(product)
            Files.write(path, bytes)
        }
        return "redirect:resources/admin/products/add"
    }
    @GetMapping("/edit/{id}")
    fun edit(@PathVariable id: Int, model: Model): String? {
        val product: Product = productRepository.getOne(id)
        val categories: List<Category> = categoryRepository.findAll()
        model.addAttribute("product", product)
        model.addAttribute("categories", categories)
        return "resources/admin/products/edit.html"
    }

    @PostMapping("/edit")
    @Throws(IOException::class)
    fun edit(
        @Valid
        product: Product,
        bindingResult: BindingResult,
        file: MultipartFile,
        redirectAttributes: RedirectAttributes,
        model: Model
    ): String? {
        val currentProduct: Product = product.id.let { productRepository.getOne(it) }
        val categories: List<Category> = categoryRepository.findAll()
        if (bindingResult.hasErrors()) {
            model.addAttribute("productName", currentProduct.name)
            model.addAttribute("categories", categories)
            return "resources/templates/admin/products/edit.html"
        }
        var fileOK = false
        val bytes = file.bytes
        val filename = file.originalFilename
        val path = Paths.get("src/main/resources/static/media/$filename")
        if (!file.isEmpty) {
            if (filename!!.endsWith("jpg") || filename.endsWith("png")) {
                fileOK = true
            }
        } else {
            fileOK = true
        }
        redirectAttributes.addFlashAttribute("message", "Product edited")
        redirectAttributes.addFlashAttribute("alertClass", "alert-success")
        val slug: String = product.name.toLowerCase().replace(" ", "-")
        val productExists: Product? = product.id.let { productRepository.findBySlugAndIdNot(slug, it) }
        if (!fileOK) {
            redirectAttributes.addFlashAttribute("message", "Image must be a jpg or a png")
            redirectAttributes.addFlashAttribute("alertClass", "alert-danger")
            redirectAttributes.addFlashAttribute("product", product)
        } else if (productExists != null) {
            redirectAttributes.addFlashAttribute("message", "Product exists, choose another")
            redirectAttributes.addFlashAttribute("alertClass", "alert-danger")
            redirectAttributes.addFlashAttribute("product", product)
        } else {
            if (!file.isEmpty) {
                val path2 = Paths.get("src/main/resources/static/media/" + currentProduct.image)
                Files.delete(path2)
                if (filename != null) {
                    product.image=filename
                }
                Files.write(path, bytes)
            } else {
                product.image=currentProduct.image// setImage(currentProduct.Image())
            }
            productRepository.save(product)
        }
        return "redirect:/admin/products/edit/" + product.id
    }

    @GetMapping("/delete/{id}")
    @Throws(IOException::class)
    fun delete(@PathVariable id: Int, redirectAttributes: RedirectAttributes): String? {
        val product: Product = productRepository.getOne(id)
        val currentProduct: Product = product.id.let { productRepository.getOne(it) }
        val path2 = Paths.get("src/main/resources/static/media/" + currentProduct.image)
        Files.delete(path2)
        productRepository.deleteById(id)
        redirectAttributes.addFlashAttribute("message", "Product deleted")
        redirectAttributes.addFlashAttribute("alertClass", "alert-success")
        return "redirect:/admin/products"
    }

}

这个问题在过去五天给我股票我不明白这个问题是从哪一方实体方/存储库方产生的。从这个问题中出来的可能方法是什么

标签: spring-bootkotlinjpa

解决方案


推荐阅读