Kotlin使用SpringData Jpa自定义存储库

时间:2017-05-20 03:05:45

标签: jpa repository spring-data kotlin

这是我的代码。我定制了我的存储库。

interface ChapterDao {
    fun test(novelId:String):List<Chapter>
}

class ChapterDaoImpl constructor(@PersistenceContext var entityManager: EntityManager){   

    fun test(novelId: String): List<Chapter> {
        val query = entityManager.createNativeQuery("select c.name, c.number from chapter c where c.novel.id = $novelId")
        val resultList = query.resultList as Array<Array<Any>>
        var chapterList:ArrayList<Chapter> = ArrayList<Chapter>()
        for (item in resultList){
            chapterList.add(Chapter(item.get(0) as String,item.get(1) as Int))
        }
        return chapterList
    }
}

interface ChapterRepository : CrudRepository<Chapter, String>, ChapterDao {

}

Chapter代码是:

package com.em248.entity;

import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import java.util.*
import javax.persistence.*

@Entity
@Table(name = "chapter")
@com.fasterxml.jackson.annotation.JsonInclude(JsonInclude.Include.NON_EMPTY)
class Chapter {
    @Id
    var id: String = UUID.randomUUID().toString()

    var number: Int = -1

    var name: String = ""

    @Column(columnDefinition = "text")
    var content: String? = ""

    @Temporal(TemporalType.TIMESTAMP)
    var createDate: Date = Date()

    @ManyToOne
    @JoinColumn(name = "novel_id")
    @JsonIgnore
    var novel: Novel = Novel();

    constructor()
    constructor(name: String, number: Int)
    constructor(number: Int, name: String, content: String?, createDate: Date, novel: Novel) {
        this.number = number
        this.name = name
        if (content != null) this.content = content
        this.createDate = createDate
        this.novel = novel
    }

}

但是当使用test函数时,会抛出错误:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property test found for type Chapter!
    at org.springframework.data.mapping.PropertyPath.lambda$new$0(PropertyPath.java:82) ~[spring-data-commons-2.0.0.M3.jar:na]
    at java.util.Optional.orElseThrow(Optional.java:290) ~[na:1.8.0_111]
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:82) ~[spring-data-commons-2.0.0.M3.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:304) ~[spring-data-commons-2.0.0.M3.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:284) ~[spring-data-commons-2.0.0.M3.jar:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243) ~[spring-data-commons-2.0.0.M3.jar:na]

我搜索如何实现自定义存储库,但我没有看到我的代码有什么不同?

1 个答案:

答案 0 :(得分:2)

ChapterDaoImpl重命名为ChapterRepositoryImpl

Spring Data查找以存储库接口+ Impl命名的自定义实现。

您根据自定义界面命名了实现。