Is it possible to automatically create relationships between entities in a database when initializing applications?

Viewed 53

At the moment I have 2 entities - Project and User. The Project object has a @ManyToMany relationship to the User object. After launching the application, I open the "project_user" table that created using "hibernate" and manually fill in the project_id and user_id columns to indicate which project is associated with which users.

But I need to use "ddl-auto: create-drop", and when I restart the application, this table has to be populated again. Can this be done automatically?

Entity Project

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "project")
public class Project {

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

    @Column
    private String name;

    @Column
    private String description;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "project_users",
            joinColumns = @JoinColumn(name = "project_id"),
            inverseJoinColumns = @JoinColumn(name = "users_id"))
    private Set<User> usersSet = new HashSet<>();

Entity User

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "users")
@JsonIgnoreProperties({"hibernateLazyInitializer"})
public class User {

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

    @Column
    private String firstName;

    @Column
    private String lastName;
1 Answers

Yes, you can use importing script files to customize the schema generation process, the hibernate.hbm2ddl.import_files configuration property must be used to provide other scripts files that Hibernate can use when the SessionFactory is started.

<property name="hibernate.hbm2ddl.import_files" value="schema-generation.sql" />

Hibernate is going to execute the script file after the schema is automatically generated.

Related