温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot中如何使用Scala

发布时间:2021-07-24 14:30:24 来源:亿速云 阅读:116 作者:Leah 栏目:编程语言

SpringBoot中如何使用Scala,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一、导入依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>2.2.1.RELEASE</version>  <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.gjing.project</groupId> <artifactId>scala-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>scala-demo</name> <description>Demo project for Spring Boot</description> <properties>  <java.version>1.8</java.version> </properties> <dependencies>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-data-jpa</artifactId>  </dependency>  <dependency>   <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId>  </dependency>  <!--加入Scala依赖库-->  <dependency>   <groupId>org.scala-lang</groupId>   <artifactId>scala-library</artifactId>   <version>2.13.1</version>  </dependency>  <dependency>   <groupId>cn.gjing</groupId>   <artifactId>tools-starter-swagger</artifactId>   <version>1.3.0</version>  </dependency>  <dependency>   <groupId>cn.gjing</groupId>   <artifactId>tools-common</artifactId>   <version>1.2.7</version>  </dependency> </dependencies> <build>  <plugins>   <!--加入Scala的编译插件,否则无法进行编译-->   <plugin>    <groupId>org.scala-tools</groupId>    <artifactId>maven-scala-plugin</artifactId>    <version>2.15.2</version>    <executions>     <execution>      <goals>       <goal>compile</goal>       <goal>testCompile</goal>      </goals>     </execution>    </executions>   </plugin>   <plugin>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-maven-plugin</artifactId>   </plugin>  </plugins> </build></project>

通过上面我们可以发现,和创建Java版本的SpringBoot项目没啥不同,只是引入了scala-library这个我们之前没引入的包,同时增加了对scala编译的插件

二、配置YML文件

server: port: 8080spring: application: name: scala-demo datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8&useSSL=false username: root password: root type: com.zaxxer.hikari.HikariDataSource hikari:  maximum-pool-size: 5  minimum-idle: 1  idle-timeout: 30000  connection-timeout: 30000 jpa: database: mysql hibernate:  ddl-auto: update # 设置创表引擎为Innodb,不然默认为MyiSam database-platform: org.hibernate.dialect.MySQL5InnoDBDialectswagger: base-package: com.gjing.project.scala.controller title: scala学习的demo

三、创建实体类

import javax.persistence._import scala.beans.BeanProperty/** * @author Gjing **/@Entity@Table(name = "scala_customer")class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @BeanProperty var id:Integer = _ @BeanProperty var customerName:String = _ def this(customerName:String){ this() this.customerName = customerName } override def toString: String = s"Customer($id,$customerName)"}

这块和我们用java开发没啥不同,只是@BeanProperty注解会帮我们生成get和set

四、Repository层

import com.gjing.project.scala.entity.Customerimport org.springframework.data.jpa.repository.JpaRepositoryimport org.springframework.stereotype.Repository/** * @author Gjing **/@Repositorytrait CustomerRepository extends JpaRepository[Customer, Integer] { /** * 通过用户名查询 * @param name 用户名 * @return Customer */ def findByCustomerName(name:String) : Customer}

这里和JAVA不同的是泛型采用的是[]中括号,这点要注意

五、Service层

import cn.gjing.tools.common.result.PageResultimport com.gjing.project.scala.entity.Customerimport com.gjing.project.scala.exceptions.MyServiceExceptionimport com.gjing.project.scala.repository.CustomerRepositoryimport javax.annotation.Resourceimport org.springframework.data.domain.Pageableimport org.springframework.stereotype.Service/** * @author Gjing **/@Serviceclass CustomerService @Resource()(customerRepository: CustomerRepository) { /** * 保存用户 * * @param name 用户名 */ def saveCustomer(name: String): Unit = { var customer = customerRepository.findByCustomerName(name) if (customer != null) {  throw MyServiceException("添加失败,用户已存在") } customer = new Customer(name) customerRepository.save(customer) } /** * 分页查询 * * @param pageable 分页对象 * @return */ def pageCustomer(pageable: Pageable): PageResult[java.util.List[Customer]] = { val page = customerRepository.findAll(pageable) return PageResult.of(page.getContent, page.getTotalPages, page.getSize, page.getTotalElements, page.getNumber) } /** * 更新用户名 * @param id 用户id * @param name 用户名 */ def updateCustomer(id: Integer, name: String): Unit = { val customer = customerRepository.findById(id).orElseThrow(() => MyServiceException("更新失败,用户不存在")) customer.setCustomerName(name) customerRepository.saveAndFlush(customer) } /** * 删除指定用户 * @param id 用户id */ def deleteCustomer(id:Integer): Unit = { val customer = customerRepository.findById(id).orElseThrow(() => MyServiceException("删除失败,用户不存在")) customerRepository.delete(customer) }}

有意思的是,在scala中依赖注入是写在类名上的

六、Controller层

import cn.gjing.tools.common.annotation.NotEmptyimport cn.gjing.tools.common.result.PageResultimport com.gjing.project.scala.entity.Customerimport com.gjing.project.scala.service.CustomerServiceimport io.swagger.annotations.{Api, ApiImplicitParam, ApiImplicitParams, ApiOperation}import javax.annotation.Resourceimport org.springframework.data.domain.PageRequestimport org.springframework.http.ResponseEntityimport org.springframework.web.bind.annotation._/** * @author Gjing **/@RestController@Api(tags = Array("用户的相关功能"))class CustomerController @Resource()(customerService:CustomerService){ @PostMapping(Array("/customer")) @ApiOperation("添加用户") @ApiImplicitParam(name = "customerName",value = "用户名",dataType = "String",required = true,paramType = "query") @NotEmpty def saveCustomer(customerName:String): ResponseEntity[String] ={ customerService.saveCustomer(customerName) ResponseEntity.ok("添加成功") } @GetMapping(Array("/customer_page")) @ApiOperation("分页查询") @ApiImplicitParams(Array( new ApiImplicitParam(name = "page",value = "页数",required = true,dataType = "int",paramType = "query"), new ApiImplicitParam(name = "size",value = "条数",required = true,dataType = "int",paramType = "query"), )) def pageCustomer(page:Integer,size:Integer): ResponseEntity[PageResult[java.util.List[Customer]]]={ ResponseEntity.ok(customerService.pageCustomer(PageRequest.of(page, size))) } @NotEmpty @PutMapping(Array("/customer")) @ApiOperation("更新用户") @ApiImplicitParams(Array( new ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "int",paramType = "query"), new ApiImplicitParam(name = "name",value = "用户名",required = true,dataType = "String",paramType = "query") )) def updateCustomer(id:Integer,name:String): ResponseEntity[String] = { customerService.updateCustomer(id, name) ResponseEntity.ok("修改成功") } @DeleteMapping(Array("/customer/{id}")) @ApiOperation("删除用户") def deleteCustomer(id:Integer): ResponseEntity[String] = { customerService.deleteCustomer(id) ResponseEntity.ok("删除成功") }}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI