【发布时间】:2019-07-03 09:50:39
【问题描述】:
我正在尝试创建两个实体(学生、大学),它们之间具有单向 @ManyToOne 关系。大学可以有很多学生。
我不想单独保存它们,我想保存学生和大学应该因为@Cascade而被保存。
在保存第二个学生期间,我遇到了异常:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
我不知道如何解决这个问题。
我的代码:
@Entity
public class Student {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne(cascade=CascadeType.ALL)
private University university;
public Student(String name, University university) {
this.name = name;
this.university = university;
}
public Student() {
}
}
@Entity
public class University {
@Id
private Long id;
private String name;
public University(Long id, String name) {
this.id = id;
this.name = name;
}
public University() {
}
}
@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {
}
@SpringBootApplication
public class App implements CommandLineRunner
{
@Autowired
private StudentRepository studentRepository;
@Autowired
private UniversityRepository universityRepository;
public static void main( String[] args )
{
SpringApplication.run(App.class);
}
@Override
public void run(String... strings) throws Exception {
Student student = new Student("pawel", new University(1L,"pw"));
Student student1 = new Student("gawel", new University(1L,"pw"));
studentRepository. save(student);
studentRepository.save(student1);
}
}
我探索过,如果除了大学参考之外我手动设置学生 ID,那么一切正常。
有效的代码:
@Entity
public class Student {
@Id
private Long id;
private String nazwa;
@ManyToOne(cascade=CascadeType.ALL)
private University university;
public Student(Long id,String nazwa, University university) {
this.id=id;
this.nazwa = nazwa;
this.university = university;
}
public Student() {
}
public Student(String nazwa) {
this.nazwa = nazwa;
}
}
@Entity
public class University {
@Id
private Long id;
private String name;
public University(Long id, String name) {
this.id = id;
this.name = name;
}
public University() {
}
}
@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {
}
@SpringBootApplication
public class App implements CommandLineRunner
{
@Autowired
private StudentRepository studentRepository;
public static void main( String[] args )
{
SpringApplication.run(App.class);
}
@Override
public void run(String... strings) throws Exception {
Student student = new Student(1L,"pawel", new University(1L,"pw"));
Student student1 = new Student(2L,"gawel", new University(1L,"pw"));
studentRepository. save(student);
studentRepository.save(student1);
}
}
为什么手动设置学生 ID 的代码有效?为什么我使用@generatedValue 时代码会出现问题?
@结果 不同之处在于,当使用@GeneratedValue 时,hibernate 创建保存查询,相比之下,当我手动分配 id 时,hibernate 首先检查数据库中是否存在实体,如果是,则实体会更新如果不是休眠第一次保存它。
【问题讨论】:
标签: java spring hibernate spring-data-jpa hibernate-mapping