1. 程式人生 > >Kotlin整合Spring Boot實現資料庫增刪改查(spring data jpa版)

Kotlin整合Spring Boot實現資料庫增刪改查(spring data jpa版)

接上次的kotlin整合spring boot的mybatis版本,這次分享的內容也很精彩,現在spring data jpa也慢慢流行起來了,因此學習kotlin的時候也順帶寫了spring data jpa版本的,下面就直接上程式碼分享給大家了

1 pom加入如下配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2 springboot的主配置檔案(配置資料來源、日誌、jpa)
server.port=8089
#DataBase DataSources
spring.datasource.url = jdbc:mysql://localhost:3306/debugxwz
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10



logging.level.com.debug=debug

# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3 實體Entity
package com.debug.pojo

import javax.persistence.Entity
import javax.persistence.Table
import javax.persistence.GenerationType
import javax.persistence.GeneratedValue
import javax.persistence.Id

@Entity
@Table(name = "user")
data class UserInfo (
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	val id:Int?=null,
	val name:String?=null,
	val address:String?=null
)
4 DAO或Repository(CRUDRepository、PagingAndSortingRepository都可,根據實際需要選擇)
package com.debug.dao

import com.debug.pojo.UserInfo
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.data.jpa.repository.Query
import org.springframework.data.jpa.repository.Modifying


interface UserDao:PagingAndSortingRepository<UserInfo, Integer> {
    //根據id獲取使用者資訊
    fun findById(id: Int): UserInfo
	
    @Query("select m from UserInfo m where m.name like %:name%")
    fun getUserInfoByName(@Param("name") name:String):List<UserInfo>
	
    @Modifying
    @Query("update UserInfo m set m.name=:name where m.id=:id")
    fun updateMemberById(@Param("name")name:String,@Param("id")id:Int) 
   
    @Modifying
    @Query("delete from UserInfo m  where m.id=:id")
    fun deleteMemberById(@Param("id")id:Int) 
	
}
5  service層
package com.debug.service

import com.debug.pojo.UserInfo
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.annotation.Propagation
import org.springframework.data.repository.query.Param

interface IUserService {
	
	fun findUserById(userId: Int): UserInfo
	fun getUserInfoByName(name:String):List<UserInfo>
	fun updateMemberById(name:String,id:Int)
	fun deleteMemberById(id:Int) 
	
	
}

package com.debug.service.impl

import com.debug.service.IUserService
import javax.annotation.Resource
import com.debug.pojo.UserInfo
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import javafx.scene.control.Pagination
import org.springframework.transaction.annotation.Propagation
import com.debug.dao.UserDao

@Service(value="userSrvice")
open class UserService:IUserService{
	@Resource
    lateinit var userDao:UserDao
	
	override fun findUserById(userId: Int):UserInfo{
		return userDao.findById(userId)
	}
	
	override fun getUserInfoByName(name:String):List<UserInfo>{
		return userDao.getUserInfoByName(name)
	}
	@Transactional(propagation=Propagation.REQUIRED)
	override fun updateMemberById(name:String,id:Int){
		return userDao.updateMemberById(name,id)
	}
	@Transactional(propagation=Propagation.REQUIRED)
	override fun deleteMemberById(id:Int) {
		return userDao.deleteMemberById(id)
	}
	
}

service層要注意處理下事務否則呼叫時會報錯

6  controller的程式碼
package com.debug.controller

import org.springframework.web.bind.annotation.RestController
import javax.annotation.Resource
import com.debug.service.IUserService
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import com.debug.pojo.UserInfo
import javax.servlet.http.HttpServletRequest
import com.debug.service.impl.UserService


@RestController
class UserController {
	
    @Resource
    lateinit var userService: IUserService;
	
    @RequestMapping("/getById")
    @ResponseBody
    fun getUserById(req:HttpServletRequest):UserInfo {
	val id:Int=Integer.parseInt(req.getParameter("id"))
        val info:UserInfo=userService.findUserById(id)
        return info
    }
    @RequestMapping("/getUserInfoByName")
    @ResponseBody
    fun getUserInfoByName(req:HttpServletRequest):List<UserInfo> {
	val name:String=req.getParameter("name")
        val info:List<UserInfo> =userService.getUserInfoByName(name)
        return info
    }
	
    @RequestMapping("/updateMemberById")
    @ResponseBody
    fun updateMemberById(req:HttpServletRequest):String {
	val name:String=req.getParameter("name")
	val id:Int=Integer.parseInt(req.getParameter("id"))
        userService.updateMemberById(name,id);
        return "資料修改成功"
    }
	
    @RequestMapping("/deleteMemberById")
    @ResponseBody
    fun deleteMemberById(req:HttpServletRequest):String {
	
	val id:Int=Integer.parseInt(req.getParameter("id"))
        userService.deleteMemberById(id);
        return "資料刪除成功"
    }
	
	
}
至此所有的程式碼編寫完成