Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin JPA Inheritance advise

What I want is to have two user types that inherit from one user super class. When I'm authenticating a user through username/password I don't care who they are at that point. However once they start making requests once logged in it will become important then.

I don't know what I should be using for the inheritance type and the repositories in kotlin for this.

@MappedSuperClass
open class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val Id: Long = 0

    val username:String = ""

    val password:String = ""
}

type1

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
data class Type1(
    val property1: String) : User
{
    val property2: String = ""
}

type2

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
data class Type2(
    val property1: String) : User
{
    val property2: String = ""
}

What I'd like to have is a user repository to be able to look at user name and password, and then repositories for the other two to get the specific properties of each. I tried

@Repository
interface UserRepository: JpaRepository<User, Long> {
    fun getUserByUsername(username: String)
}

and then

@Repository
interface Type1Repository: UserRepository<Type1, Long>

but it wouldn't accept the <> in the type 1 repository.

I haven't found a good resource talking about this for kotlin yet. If you know of one please pass it along. Thanks.

like image 829
Cate Daniel Avatar asked Sep 14 '25 00:09

Cate Daniel


1 Answers

Like shown in here: https://ideone.com/JmqsDn you are just missing the types in your intermediate interface, ie.:

interface UserRepository<User, Long>: JpaRepository<User, Long> {
    fun getUserByUsername(username: String)
}

Side note: kotlin 1.1+ is required for data classes to inherit from other classes.

like image 130
guido Avatar answered Sep 16 '25 17:09

guido