Scala代码开发 metaTable(元表)

时间:2022-05-23 23:09:30

使用Scala语言开发时,自动生成get和set方法

不用写return进行返回, 因为它的最后一行就是返回值

先建立四个层(层层递进)

domain 表结构的建立

repository(DAO) 实现接口层

service 实现业务层

controller 实现控制层

domain层开发

MetaTable.scala

package com.imooc.imoocbootscala.domain

import javax.persistence.{Entity, GeneratedValue, Id, Table}

import scala.beans.BeanProperty

/**
* 使用Scala语言开发时,自动生成get和set方法
* 不用写return进行返回, 因为它的最后一行就是返回值
*/
@Entity
@Table
class MetaTable { @Id
@GeneratedValue
@BeanProperty
var id:Integer = _ @BeanProperty
var name:String = _ @BeanProperty
var tableType:String = _ @BeanProperty
var dbId:Integer = _
}

repository层开发

MetaTableRepository.scala

package com.imooc.imoocbootscala.repository

import com.imooc.imoocbootscala.domain.MetaTable
import org.springframework.data.repository.CrudRepository trait MetaTableRepository extends CrudRepository[MetaTable, Integer]{ }

serive层开发

MetaTableService.scala

package com.imooc.imoocbootscala.service

import com.imooc.imoocbootscala.domain.MetaTable
import com.imooc.imoocbootscala.repository.MetaTableRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional /**
*
* 注意,导入的注解包和java的完全不一样
*/
@Service
class MetaTableService @Autowired()(metaTableRepository: MetaTableRepository){ @Transactional //事务
def save(metaTable:MetaTable)= {
metaTableRepository.save(metaTable)
} def query() = {
metaTableRepository.findAll()
} }

controller层开发

MetaTableController.scala

package com.imooc.imoocbootscala.controller

import com.imooc.imoocbootscala.domain.MetaTable
import com.imooc.imoocbootscala.service.MetaTableService
import com.imooc.imoocbootscala.utils.ResultVOUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation._ @RestController
@RequestMapping(Array("/meta/table"))
class MetaTableController @Autowired()(metaTableService: MetaTableService){ @RequestMapping(value = Array("/"), method = Array(RequestMethod.POST))
@ResponseBody
def save(@ModelAttribute metaTable:MetaTable) = {
metaTableService.save(metaTable)
ResultVOUtil.success() // 此处就是Scala调用已有的Java代码
} @RequestMapping(value = Array("/"), method = Array(RequestMethod.GET))
@RequestBody
def query() = {
ResultVOUtil.success(metaTableService.query())
} }

属性值:

application.yml

server:
port: 7777
context-path: /scala-boot
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/bootscala?useSSL=false
jpa:
hibernate:
ddl-auto: update
database: mysql

功能测试:

运行代码,在控制台查看,是否运行成功
在IDEA控制台查看信息:
Scala代码开发 metaTable(元表)

去终端中的mysql下查看信息:
Scala代码开发 metaTable(元表)

用postman软件,进行测试:

save()方法的测试:
Scala代码开发 metaTable(元表)

query()方法的测试:
Scala代码开发 metaTable(元表)