kotlin+springboot(1)

最近流行kotlin,就赶紧趁热来一波实战。
一开始使用idea自动创建kotlin-springboot项目,创建完之后整个人傻掉了,一脸懵逼。只好rm -rf ,重新创建了个java的脚手架。😳

然后,正片开始...

这次先测试了整合data-jpa:
先创建实体类 Note.kt

package com.udc.domin.note

import java.util.*
import javax.persistence.*

/**
 * Created by zhangjiqiang on 2017/6/1.
 */
@Entity
class Note{

    @Id
    @GeneratedValue
     var id: Long? = null

     var author: String? = null

     var title: String? = null

     var type: String? = null

     var status: Int? = null

     var kw: String? = null

     var mdHtml: String? = null

    @Lob
     var content: String? = null

    @Temporal(TemporalType.TIMESTAMP)
     var createTime: Date? = null

    @Temporal(TemporalType.TIMESTAMP)
     var updateTime: Date? = null

}

然后,创建repository

package com.udc.domin.note

import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

/**
 * Created by zhangjiqiang on 2017/6/1.
 */
@Repository
interface NoteRepository : JpaRepository<Note, Long> {
    fun findByTitle(title: String): List<Note>
    fun findAll(status: Specification<Note>, page: Pageable)
    fun findById(id: Long): Note
}

再来个测试类!

package com.udc

import com.udc.domin.note.Note
import com.udc.domin.note.NoteRepository
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner

/**
 * Created by zhangjiqiang on 2017/6/1.
 */
@RunWith(SpringRunner::class)
@SpringBootTest
class Test{

    @Autowired
    val noteRepository: NoteRepository? = null

    @Test
    fun contextLoads() {
        var note=Note()
        note.author="yangxyxxxx"
        note.kw="ssssss"
        noteRepository?.save(note)
        val list = noteRepository?.findByTitle("x2")
        println(if (list == null) "null" else list!!.size)
        println(list!!.get(0).content)
    }
}

这里踩了个小坑。说明一下,在创建Note的时候,一开始属性是用val 声明的,然后这里给对象赋值就会报错,所以Note里的所有属性都改成了var声明 😅

val list = noteRepository?.findByTitle("x2")
println(if (list == null) "null" else list!!.size)
println(list!!.get(0).content)

这里的?表示返回可能为null,使用的时候要小心了。
下面的 println(list!!.get(0).content),嗯,为什么要这么写,为什么这么写,为什么这,为什么,,看我的眼神就行了...😮😮😮😮
list!!.get(0).content
等价于
if (list != null) {
println(list.get(0).content)
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容