【问题标题】:@ManyToOne, foreign key or both?@ManyToOne,外键还是两者兼而有之?
【发布时间】:2017-01-29 20:45:15
【问题描述】:

这可能是一个重复的问题,也可能是一个非常基本的问题,但我需要一些帮助...

所以我正在使用 Spring Boot 构建一个应用程序,我有学生和班级,许多学生可以在一个班级中,所以这是多对一的。这就是我所做的:

@Entity 
@Data 
public class Eleve implements Serializable{

@Id
@GeneratedValue
private int idEt;
private String nomEt;
private String prenomEt;
@Column(length=1)
private String sexe;
private Date dobEt;
private String adresseEt;
private String telEt;
private String parentName;
private Date dateInscription;
private Date dateSortie;

@ManyToOne
private Classe classe;

}

这是有效的,我在 eleve 表中看到了classe_id_cl,但它不是foreign_key!此列可以接受任何值。

更新 顺便说一句,这是我的 application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-edss
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.session.store-type=none
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

我需要使用flywayDB之类的东西并强制它成为foreign_key吗?

【问题讨论】:

    标签: database spring jpa


    【解决方案1】:

    您应该在多对一映射中指定连接列:

    @ManyToOne
    @JoinColumn(name = "columnname")
    private Classe classe;
    

    更新

    好的,根据您的 application.properties,您使用的方言不支持外键约束。

    正确的配置应该是:

    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    

    【讨论】:

    • 所以您指的是启动期间的自动模式创建?
    • 暂时是,spring.jpa.hibernate.ddl-auto=create
    • 您是否在 Classe 实体上添加了@OneToMany 映射?
    • 我只是指定一种方式。我的意思是仅在 Etudiant 实体中
    • 好的,让我们现在就发帖...请将属性添加到问题中,我会更新答案。以便其他用户可以从中受益。错误的属性.. 以便清楚什么是错误的
    猜你喜欢
    • 2014-07-20
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2010-10-20
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多