Maor Cohen
Maor Cohen

Reputation: 21

Sprinng Data JPA using OneToOne relationship (Hibernate)

I am using this simple example from baeldung (section 3.2). I have a Spring web application with two additional classes:

User.java:


    @Entity
    @Table(name = "users")
    public class User {
        
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        private Long id;
        //... 
    
        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "address_id", referencedColumnName = "id")
        private Address address;
    
        // ... getters and setters
    }

 

Address.java:


    @Entity
    @Table(name = "address")
    public class Address {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        private Long id;
        //...
    
        @OneToOne(mappedBy = "address")
        private User user;
    
        //... getters and setters
    }

When I run the application I get the following error:

GenerationTarget encountered exception accepting command : Error executing DDL "alter table users drop foreign key FKditu6lr4ek16tkxtdsne0gxib" via JDBC [Table 'sys.users' doesn't exist]

What is the problem with my code?

application.yml:


    spring:
      application:
        name: auction
      datasource:
        url: jdbc:mysql://localhost:9708/sys
        username: root
        password: pass
        driver-class-name: com.mysql.cj.jdbc.Driver
      jpa:
        hibernate:
          ddl-auto: create-drop
        database: mysql
        show-sql: true

Upvotes: 0

Views: 72

Answers (1)

Manuel
Manuel

Reputation: 4238

Most likely users is in your database an already existing table, e.g., build-in. Change your table name to something else.

In addition, do NOT use any CASCADE= on your owning (child) side of the mapping, that is a code smell. As you child is the owner of the relation ship, no CASCADE is necessary. CASCADEs may be placed (with care) on the non-owning (parent) side.

Upvotes: 0

Related Questions