Home > Back-end >  Spring Boot Hibernate creates tables with wrong names
Spring Boot Hibernate creates tables with wrong names

Time:10-21

When I run my project, the Hibernate creates automatically tables with wrong names. I have two tables User and Role and also three classes: abstract class IdField.java:

@Entity
public abstract class IdField {

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;
    //constructors and getters setters

User.java class:

@Entity
@Table(name = "user", schema = "quiz_app")
public class User extends IdField{

    @Column(name = "user_name")
    private String userName;
    @Column(name = "password")
    private String password;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;

    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<Role> roles = new ArrayList<>();
    //constructors and getters setters

and Role.java class:

@Entity
@Table(name = "role", schema = "quiz_app")
public class Role extends IdField{

    @Enumerated(EnumType.ORDINAL)
    @Column(name = "role_name")
    private RoleName roleName;
    //constructors and getters setters

And Hibernate creates two tables with wrong names as id_field and id_field_roles: enter image description here

but I want table names as it is in @Table annotation like "user" and "role"

CodePudding user response:

Get familiar with inheritance strategies:

https://thorben-janssen.com/complete-guide-inheritance-strategies-jpa-hibernate/

It seems to me you are looking for @MappedSuperclass

If you just want to share state and mapping information between your entities, the mapped superclass strategy is a good fit and easy to implement. You just have to set up your inheritance structure, annotate the mapping information for all attributes and add the @MappedSuperclass annotation to your superclass. Without the @MappedSuperclass annotation, Hibernate will ignore the mapping information of your superclass.

On top of that: If your shared part is only id field, as the name suggests, inheritance looks like overkill.

  • Related