Springboot之kotlin&java

Introduction

We all know that java is an object-oriented programming language, but in fact, there is some complexity in writing code. Even if jdk8 appears later to increase the convenience of code development, it is still not concise enough. Even if a powerful jvm is used as a running environment, it is difficult for all major environments It runs with each other, Google advocates the development of kotlin language, and at the same time it is embedded in Android, which can be developed without plug-ins. I won’t give too much introduction to the advantages and disadvantages of languages. Each language has its own shortcomings and advantages, which are mainly carried out according to the project situation. But in fact, I still recommend to use java, after all, java is more common and there are more learning materials at present! Next, we live in gradle to build Kotlin's RestFul project.

Example

Introduction to technical system

  1. This application editing tool is idea, because the new version of the idea version tool has a kotlin plugin
  2. The database is a mysql service in docker
  3. The basic environment is jdk8
  4. spring boot as a technical framework

Operating procedures

Build mysql&jdk

Mysql builds
the mysql startup file docker-compose.yaml of docker:

version: '2'

services:
  mysql:
    image: mysql:5.7
    command: [mysqld, --character-set-server=utf8mb4, --collation-server=utf8mb4_unicode_ci]
    environment:
      MYSQL_ROOT_PASSWORD: root
      TZ: Asia/Shanghai
    ports:
      - "3307:3306"
    volumes: 
      - "~/data/mysql:/var/lib/mysql"

Create the above file (touch docker-compose.yaml), start the mysql service in the current directory, docker-compose up -d
jdk configuration
JAVA_HOME = your jdk home directory
PATH = JAVAHOME / bin: JAVA_HOME/bin:JAVAHOME/bin:PATH:.
CLASSPATH= J A V A H O M E / l i b / t o o l s . j a r : JAVA_HOME/lib/tools.jar: JAVAHOME/lib/tools.jar:JAVA_HOME/lib/dt.jar:.
export JAVA_HOME
export CLASSPATH

Initialize spring boot

Here is the official website initialization method link , as shown in the following figure: The
Insert picture description here
gradler package is loaded as follows:

	implementation("org.springframework.boot:spring-boot-starter-data-jpa")
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
	implementation("org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final")
	runtimeOnly("mysql:mysql-connector-java")
	testImplementation("org.springframework.boot:spring-boot-starter-test")

Project package structure

Insert picture description here

application file

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3307/kotlin
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    dbcp2:
      test-while-idle: true
      validation-query: SELECT 1
  jpa:
    database: MYSQL
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

Start the class and add the sweep pathInsert picture description here

File data class

// Config 类
package com.lgh.run.config
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.ComponentScan
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@ComponentScan("com.lgh")
@EntityScan("com.lgh.entity")
@EnableJpaRepositories("com.lgh.repository")
class Config

// DemoApplication 类
package com.lgh.run
import com.lgh.run.config.Config
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Import
@SpringBootApplication
@Import(Config::class)
class DemoApplication
fun main(args: Array<String>) {
    
    
	runApplication<DemoApplication>(*args)
}

// User
package com.lgh.entity
import javax.persistence.*
@Entity
class User(
        @Id @GeneratedValue(strategy = GenerationType.AUTO) val id:Long?,
        @Column(name = "user_id") val userId:Long?,
        @Column(name = "user_name") val userName:String?
)

// UserRepository
package com.lgh.repository
import com.lgh.entity.User
import org.springframework.data.repository.CrudRepository
interface UserRepository: CrudRepository<User,Long>{
    
    
    fun findByUserNameLike(uName:String):Collection<User>?
    fun findByUserId(uId:Long):User?
}

// UserServiceImpl 类
package com.lgh.service
import com.lgh.entity.User
import com.lgh.repository.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class UserServiceImpl {
    
    
    @Autowired
    val userRepository: UserRepository? = null
    fun findByUName(uName: String): Collection<User>? = userRepository?.findByUserNameLike(uName?.plus("%"))
    fun findByUId(id:Long): User? = userRepository?.findByUserId(id)
}

# UserRepository
package com.lgh.repository
import com.lgh.entity.User
import org.springframework.data.repository.CrudRepository
interface UserRepository: CrudRepository<User,Long>{
    
    
    fun findByUserNameLike(uName:String):Collection<User>?
    fun findByUserId(uId:Long):User?
}

// UserController
package com.lgh.controller
import com.lgh.entity.User
import com.lgh.service.UserServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/users")
class UserController {
    
    
    @Autowired
    val userService: UserServiceImpl? = null
    @GetMapping("/id/{id}")
    fun findUserById(@PathVariable("id") id: Long): User? = userService?.findByUId(id)
    @GetMapping("/name/{userName}")
    fun  findByUserName(@PathVariable("userName") userName:String): Collection<User>? = userService?.findByUName(userName)
}

Source address

github

Summary & reflection

Leave it to the viewer to summarize and reflect!

Guess you like

Origin blog.csdn.net/soft_z1302/article/details/112388727