如何使用关系OneToOne将两个相关对象保存到数据库 [英] How to save two related objects to data base with relation OneToOne
问题描述
当我尝试保存U对象时,出现下一个异常:
When I'm trying to save an U object I got next exception:
org.springframework.orm.jpa.JpaSystemException:尝试从空的一对一属性[com.roc.domain.A.user]分配ID;嵌套的异常是org.hibernate.id.IdentifierGenerationException:尝试从空的一对一属性[com.roc.domain.A.user]中分配ID.
org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.roc.domain.A.user]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.roc.domain.A.user]
我有两个表: 1.用户,其列为id(自动incr,primary),名称. 2.与该列联系的是id,user_id(即外键-> user.id)和地址.
I have two tables: 1. user that columns are id(auto incr, primary), name. 2. contact that columns are id, user_id(that is foreign key -> user.id) and address.
@Entity
@Table(name = "a")
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name="address")
private String address;
@OneToOne
@MapsId
private U user;
public A() {
}
// getters and setters
}
@Entity
@Table(name = "u")
public class U {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name="username")
private String userName;
@JoinColumn(name = "user_id", referencedColumnName = "id")
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private A a;
public U(){};
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Autowired
private URepository uRepository;
@Test
public void simpleCrudTest() {
U user = new U("name", new A("address"));
uRepository.save(user);
}
}
推荐答案
您已经正确设置了层叠,但是由于这种关系是双向的,因此您需要在内存模型中设置双方.
You have set the cascade correctly however because the relationship is bi-directional you need to set both sides in the in-memory model.
@Test
public void simpleCrudTest() {
U user = new U("name", new A("address"));
//will work when this is added
a.setUser(user);
uRepository.save(user);
}
否则,由于错误状态,A在保存时为用户提供了空引用.
Otherwise, as the error states, A has a null reference for user on save.
这篇关于如何使用关系OneToOne将两个相关对象保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!