【发布时间】:2018-01-17 03:38:59
【问题描述】:
我有两个实体:帐户和个人资料。它们以一对一的关系联系在一起。
账户实体:
@Entity
@Table(name = "account")
public class Account {
@Id
@Column(name = "account_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
private Profile profile;
...
}
个人资料实体:
@Entity
@Table(name = "profile")
public class Profile {
@Id
@Column(name = "profile_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(mappedBy = "profile", cascade = CascadeType.ALL)
private Account account;
...
}
问题是当我尝试在数据库中保存一个来自 Account 的新对象和一个来自 Profile 的新对象并连接它们时。像这样的:
Account account = new Account();
Profile profile = new Profile();
profile.setAccount(account);
account.setProfile(profile);
accountRepository.save(account);
profileRepository.save(profile);
这当然行不通。在寻找解决方案后,我发现我必须使用持久方法和事务。但是我还没有找到如何使用它们。我尝试使用EntityManager并创建一个persistence.xml文件,但是spring没有找到它(我把它放在目录:src/main/resources/Meta-INF)。
我的问题是:有没有更简单的方法来保存这两个对象(无需创建新的 xml 文件等)?如果没有我必须做什么才能让它发挥作用?
我在带有 Maven 的 Netbeans 中使用 spring 和 hibernate 和 mysql。
【问题讨论】:
标签: spring hibernate maven netbeans spring-data-jpa