Skip to content
Advertisement

Can’t create one_to_one relationship: Unknown mappedBy in

I try to create an OneToOne relationship between two tables but I receive errors.

I used a lot of tutorials but nothing helps. For example baeldung tutorial:

Project structure:

@Entity
@Table(name="user")
public class User{

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "personal_data_id")
    private PersonalData personalData;

//getters, setters
}

@Entity
@Table(name = "personal_data")
public class PersonalData {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToOne(mappedBy = "personal_data")
    private User user;

//getters, setters
}


The error:

Caused by: org.hibernate.AnnotationException: Unknown mappedBy in: com....dto.PersonalData.user, referenced property unknown: com...dto.User.personal_data

Gradle:

plugins {
    id 'org.springframework.boot' version '2.7.3'
    id 'io.spring.dependency-management' version '1.0.13.RELEASE'
    id 'java'
}

group = 'com.hltr'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
    implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.30'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

application.properties:

#Database settings
spring.datasource.url=jdbc:mysql://localhost:3306/db?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.datasource.tomcat.connection-properties=useUnicode=true;characterEncoding=utf-8;
spring.datasource.sql-script-encoding=UTF-8
spring.jpa.open-in-view=false

#Disable thymeleaf cashing
spring.template.cache = false;


Advertisement

Answer

You need to use a field name for mappedby, not a column name.

In you case, it should be @OneToOne(mappedBy = "personalData").

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement