Spring Boot自动生成MySQL数据库



我正在尝试基于POJO类自动生成数据库:

控制器型号:

@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
}

电影模型:

@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
}

在这里审计模型,它有像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
}

这是我在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

我正在使用spring.jpa.hibernate.ddl-auto=update自动生成数据库。现在数据库生成得很好,但是外键是作为一个简单的整数字段生成的。

您有ManyToOne,但控制器类中缺少OneToMany

在您的导演类中,您应该添加类似的内容

@OneToMany
@JoinColumn(name = “director”)
private List<Director> items;

你能试试spring.jpa.hibernate.ddl-auto=create

它将删除所有MySQL表并创建新表。稍后返回update

这是正确的行为。在数据库中,foregin键引用其他表中的主键。在您的情况下,它是一个整数。ORM框架将主键关系转化为对象关联(反之亦然(。

相关内容

  • 没有找到相关文章