3

I'm using Spring Jpa with Kotlin, i got 2 tables, first is an user table, second is refresh token table, where column user_id references on users.id column

I'm trying to create OneToOne relationship between these 2 tables

Here's my user entity

@Entity
@Table(name = "users")
class User (
    val name: String

    @OneToOne(mappedBy = "user", cascade = [CascadeType.ALL])
    val refreshToken: Token? = null
) : : AbstractBaseEntity<Long>()

And Token entity

@Table(name = "user_refresh_token")
@Entity
class Token (
        var token: String,
        val userId: Long,

        @MapsId
        @OneToOne
        val user: User? = null

) : AbstractBaseEntity<Long>() 

AbstractBaseEntity contains only Id field

@MappedSuperclass
abstract class AbstractBaseEntity<T> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: T? = null

}

In my Postgres database it looks like

create table users (
    id serial primary key,
    name text not null
);

create table user_refresh_token (
    user_id int primary key references users(id) on delete cascade,
    token text not null
)

In logs i see the error

Caused by: org.hibernate.DuplicateMappingException: Table [user_refresh_token] contains physical column name [user_id] referred to by multiple logical column names: [user_id], [userId]

Also my TokenRepository

@Repository
interface TokenRepository : CrudRepository<Token, Long>

I can't figure out why it's happening and why column user_id referred to multiple column names, any ideas?

Yar Sol
  • 197
  • 2
  • 15

1 Answers1

2

In Token class you should keep either val userId: Long or val user: User? (better option), not both of them

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
  • In fact Hibernate allows to have several mapping as long as logical names are the same (and all except one are `updatable=false, insertable=false`, See https://stackoverflow.com/questions/30090941/jpa-readonly-mapping/ – gavenkoa Jan 10 '23 at 23:38