Geo*_* Z. 3 java orm hibernate jpa spring-boot
我正在尝试在 a和 a之间@OneToOne使用相同的方法来实现关联。A有一个可选的,但 a有一个必需的(因此我需要在“cars”表内有一个外键指向现有的):@IdCarPersonPersonCarCarPersonPerson
@Entity
@Table(name = "persons")
public class Person {
@Id
@Column(name = "name")
private String name;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "person")
private Car car;
/**
* For hibernate
*/
@SuppressWarnings("unused")
private Person() {
}
public Person(String name) {
super();
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
@Entity
@Table(name = "cars")
public class Car {
@Id
@Column(name = "name")
private String name;
@MapsId
@OneToOne
@JoinColumn(name = "name")
@OnDelete(action = OnDeleteAction.CASCADE)
private Person person;
public Car() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Run Code Online (Sandbox Code Playgroud)
public interface PersonRepository extends CrudRepository<Person, String> {
}
Run Code Online (Sandbox Code Playgroud)
我的测试用例:
@Autowired
private PersonRepository personRepository;
@Test
public void test() {
Person mike = new Person("Mike");
personRepository.save(mike); //Saved sucessfully
Person alice = new Person("Alice");
Car car = new Car();
car.setPerson(alice);
car.setName(alice.getName());
alice.setCar(car);
personRepository.save(alice); //error
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
org.springframework.orm.jpa.JpaSystemException:尝试从 null 一对一属性 [com.project.entity.Car.person] 分配 id;嵌套异常是 org.hibernate.id.IdentifierGenerationException:尝试从 null 一对一属性 [com.project.entity.Car.person] 分配 id
我按照这个解决方案了解如何拥有共享 ID。数据库中的架构看起来很好,并且完全按照我想要的方式工作。如果我删除一辆车,什么也不会发生。如果我删除拥有 a 的人Car,他Car也会从数据库中删除。
问题很简单。我做错了什么?
如果它发挥任何作用(我对此表示怀疑),这是我的数据源属性:
spring.jpa.hibernate.dll-auto = create-drop
spring.datasource.url=jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
Run Code Online (Sandbox Code Playgroud)
(免责声明:这并不是问答)
问题出在@MapsId注释上。将其更改为:
@MapsId("name") //Here
@OneToOne
@JoinColumn(name = "name")
@OnDelete(action = OnDeleteAction.CASCADE)
private Person person;
Run Code Online (Sandbox Code Playgroud)
似乎解决了问题。
| 归档时间: |
|
| 查看次数: |
2288 次 |
| 最近记录: |