I'm trying to auto generate the database based on POJO classes :
Director Model :
@Entity
@Table(name = "director")
public class Director extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "age", nullable = false)
private int age;
@Column(name = "description", nullable = false)
private String description;
@Column(name = "photo", nullable = false)
private String photo;
//Getters & Setters
}
Movie Model :
@Entity
@Table(name = "movie")
public class Movie extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "story", nullable = false)
private String story;
@Column(name = "photo", nullable = false)
private String photo;
@Column(name = "releaseYear", nullable = false)
private int releaseYear;
@Column(name = "rating", nullable = false)
private float rating;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "director", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Director director;
//Getters & Setters
}
And here Audit Model which have Temporal fields like created_at ...
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public abstract class AuditModel implements Serializable {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", nullable = false, updatable = false, columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at", nullable = false, columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@LastModifiedDate
private Date updatedAt;
// Getters & Setters
}
And here's my configuration in application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_movies
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jackson.serialization.fail-on-empty-beans=false
I'm using spring.jpa.hibernate.ddl-auto=update to auto-generate the database.
Now the database is generated good, but the foreign key is generated as a simple integer field.
You have ManyToOne but OneToMany is missing in Director Class
In your Director Class you should add something like this
@OneToMany
@JoinColumn(name = “director”)
private List<Director> items;
and Can you try spring.jpa.hibernate.ddl-auto=create
It will delete all MySQL tables and Create new Tables. Later on CHange back to update