Kotlin SpringJPA One-to-One relationship

In the tutorial, JavaSampleApproach will show you the way to create an Kotlin SpringJPA One-to-One relationship application with SpringBoot.

Related posts:
Kotlin SpringJPA Many-To-Many relationship
Kotlin SpringJPA Hibernate One-To-Many relationship
How to configure Spring JPA One to One Relationship – SpringBoot

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.6.RELEASE
– MySQL Database
– Kotlin language

II. Practice

In the tutorial, We create a Kotlin SpringBoot project that have 2 entities {Wife, Husband} with One-To-One relationship as below:

kotlin springjpa one-to-one - relationship

Project Structure:

kotlin springjpa one-to-one - project structure

Step to do:
– Create Kotlin SpringBoot project
– Create Kotlin data models
– Create Spring JPA repositories
– Implement RestController
– Run and check results

1. Create Kotlin SpringBoot project

Using SpringToolSuite to create a Kotlin SpringBoot project.

>>> More step details, you can follow below tutorial:

Then add needed dependencies:

[...]

<properties>
	<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
	<kotlin.version>1.1.4</kotlin.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	
	<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>
		<scope>runtime</scope>
	</dependency>
	
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-stdlib-jre8</artifactId>
		<version>${kotlin.version}</version>
	</dependency>
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-reflect</artifactId>
		<version>${kotlin.version}</version>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

[...]

2. Create Kotlin data models

Create 2 Kotlin data model:

Wife.kt:


package com.javasampleapproach.kotlin.onetoone.model

import javax.persistence.CascadeType
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.OneToOne
import javax.persistence.Table

@Entity
@Table(name="wife")
data class Wife(
	val name: String = "",
	
	@OneToOne(cascade = arrayOf(CascadeType.ALL))
    @JoinColumn(name = "husband_id")
	val husband: Husband ?= null,
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	val id: Long = 0
){
	override fun toString(): String{
		return "{wife: ${this.name}, husband: ${husband?.name}}"
	}
}

Husband.kt:


package com.javasampleapproach.kotlin.onetoone.model

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

@Entity
@Table(name="husband")
data class Husband(
	val name: String = "",
	
	@OneToOne(mappedBy = "husband")
	val wife: Wife? = null,
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	val id: Long= 0
){
	override fun toString(): String{
		return "{husband: ${this.name}, wife: ${wife?.name}}";
	}
}

3. Create Spring JPA repositories

Using interface JpaRepository to create 2 repositories:

interface WifeRepository:


package com.javasampleapproach.kotlin.onetoone.repo

import com.javasampleapproach.kotlin.onetoone.model.Wife
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface WifeRepository  : JpaRepository{
}

interface HusbandRepository:


package com.javasampleapproach.kotlin.onetoone.repo

import com.javasampleapproach.kotlin.onetoone.model.Husband
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface HusbandRepository : JpaRepository{
}

@Entity: Specifies that the class is an entity. This annotation is applied to the entity class.
@Id: Specifies the primary key of an entity.
@OneToOne: Defines a single-valued association to another entity that has one-to-one multiplicity.
@JoinColumn: Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

Now open application.properties file, add configuration:


spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=12345
 
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

4. Implement RestController

Implement a Kotlin RestController RestAPIsController with 4 APIs:

– For delete all data from tables, we create an API: /api/clear
– For saving entities, We implement an API: /api/save
– For retrieve entities, We implement 2 APIs
-> /api/students: fetch all Student entities from database.
-> /api/subjects: fetch all Subject entities from database.


package com.javasampleapproach.kotlin.onetoone.controller

import com.javasampleapproach.kotlin.onetoone.model.Husband
import com.javasampleapproach.kotlin.onetoone.model.Wife
import com.javasampleapproach.kotlin.onetoone.repo.HusbandRepository
import com.javasampleapproach.kotlin.onetoone.repo.WifeRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.transaction.Transactional

@RestController
@RequestMapping("/api")
class RestAPIsController {
	@Autowired
	lateinit var wifeRepository: WifeRepository
	
	@Autowired
	lateinit var husbandRepository: HusbandRepository

	@RequestMapping("/clear")
	fun clearData(): String {
		// clean data of tables before saving
		wifeRepository.deleteAll()
		husbandRepository.deleteAll()
		
		return "Done!"		
	}
		
	@RequestMapping("/save")
	fun save(): String {
		// save a wife to DB
		wifeRepository.save(Wife("Lisa", Husband("David")))
 
        // save list of wifes to DB
        wifeRepository.save(listOf(Wife("Mary", Husband("Peter")),
									Wife("Lauren", Husband("Phillip"))))
		
		return "Done!"
	}
	
	@RequestMapping("/wifes")
	fun retrieveAllWifes(): String{
		val wifes = wifeRepository.findAll();
		
		// some processing for better String format on browser showing 
		var info : String = ""
		wifes.forEach{
			info += it.toString() + "
" } return info } @RequestMapping("/husbands") fun retrieveAllHusbands(): String{ val husbands = husbandRepository.findAll() // some processing for better String format on browser showing var info : String = "" husbands.forEach{ info += it.toString() + "
" } return info } }

5. Run and check results

Build and Run the Kotlin SpringBoot project by commanlines {mvn clean install, mvn spring-boot:run}.

– To make sure a clean database tables before working, we make a clear request: http://localhost:8080/api/clear

kotlin springjpa one-to-one - clear request

– Make a saving request: http://localhost:8080/api/save

kotlin springjpa one-to-one - save request

-> Check database’s results:

kotlin springjpa one-to-one - all tables

– Retrieve Wife entities: http://localhost:8080/api/wifes
-> Result:

kotlin springjpa one-to-one - wifes request

– Retrieve Husband entities: http://localhost:8080/api/husbands
-> Result:

kotlin springjpa one-to-one - husband request

III. Sourcecode

KotlinSpringJPAOneToOne

3 thoughts on “Kotlin SpringJPA One-to-One relationship”

  1. I’ll immediately grasp your rss feed as I can’t in finding your
    email subscription link or newsletter service. Do
    you’ve any? Please permit me recognize in order that
    I may subscribe. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *