问题描述
我有这些实体。
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Language {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String language;
}
和
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Sentence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String wordInfrench;
@NotNull
private String wordInOtherLanguage;
@ManyToOne
@NotNull
private Language language;
}
当我尝试通过使用以下代码将行插入sentence
数据库中时:
// My repository
private SentenceRepository sentenceRepository;
// Object information
Long id = 0L;
String wordInfrench = "Oui oui"
String wordInOtherLanguage = "Ja ja"
Language language = new Language(id,"Swedish");
// Save to database
sentenceRepository.save(new Sentence(id,wordInfrench,wordInOtherLanguage,language));
我收到此错误:
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find
se.danielmartensson.entity.Language with id 0; nested exception is javax.persistence.EntityNotFoundException: Unable to find se.danielmartensson.entity.Language with id 0
Caused by: javax.persistence.EntityNotFoundException: Unable to find se.danielmartensson.entity.Language with id 0
如果我使用Long id = 1L;
,也会出现此错误:
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find
se.danielmartensson.entity.Language with id 1; nested exception is javax.persistence.EntityNotFoundException: Unable to find se.danielmartensson.entity.Language with id 1
Caused by: javax.persistence.EntityNotFoundException: Unable to find se.danielmartensson.entity.Language with id 1
那是怎么回事?为什么不能将sentence
插入数据库,而language
数据库也将更新?
解决方法
问题是Hibernate试图在数据库中找到id = 0(和1)的Language
实例,但是它不存在。
首先,您必须插入语言,然后才能插入句子:
// My repositories
private LanguageRepository languageRepository;
private SentenceRepository sentenceRepository;
// Inserting the Language
Language language = new Language();
language.setLanguage("Swedish");
// Here,note that I'm not forcing the value of the attribute "id".
// The "@GeneratedValue" will generate one for me.
// Also note that the "save" method returns an object. In this case,// it will be a "Language" instance with the new id
language = languageRepository.save(language);
// Inserting the Sentence
Sentence sentence = new Sentence();
sentence.setWordInFrench("Oui oui");
sentence.setWordInOtherLanguage("Ja ja");
sentence.setLanguage(language);
sentenceRepository.save(sentence);
或者,您可以执行以下操作:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Sentence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String wordInFrench;
@NotNull
private String wordInOtherLanguage;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "id_language",nullable = false)
private Language language;
我们使用cascade = CascadeType.PERSIST
表示每次尝试插入新句子时,Hibernate都会自动检查数据库中是否已经存在language
对象。否则,将language
预先插入。
此外,对于外键,建议使用@JoinColumn
映射来配置列定义,例如“名称”,“可空”,“唯一”等。