【发布时间】:2019-06-29 15:30:28
【问题描述】:
我无法更新依赖对象列表。我有一个 API 应该更新与客户的帐户列表。 一个客户 - 多个帐户。
我按照指示配置了 @OneToMany 以进行正确更新:
@OneToMany(mappedBy = "client", orphanRemoval = true, cascade = CascadeType.ALL)
实体:
@Entity
@Getter
@Setter
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id_client")
private Integer id;
private String name;
private int age;
@OneToMany(mappedBy = "client", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Account> accounts = new ArrayList<>();
}
@Entity
@Getter
@Setter
public class Account {
@Id
@GeneratedValue
@Column(name = "id_account")
private Integer id;
private int amount;
private String currency;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_client")
private Client client;
}
我想对提供的数据做什么。我已经有一个客户 (id = 100) 有两个帐户 (id = 10, 11)。
我想更新,以便客户端具有不同的帐户 ID 列表:10、12。
我的测试用测试数据。
<dataset>
<Client id_client="100" name="John" age="23"/>
<Client id_client="101" name="Mike" age="28"/>
<Client id_client="102" name="Kevin" age="19"/>
<Account id_account="10" amount="50" currency="USD" id_client="100"/>
<Account id_account="11" amount="100" currency="USD" id_client="100"/>
<Account id_account="12" amount="150" currency="EUR" id_client="101"/>
<Account id_account="13" amount="200" currency="EUR" id_client="102"/>
</dataset>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
@Transactional
@DatabaseSetup("/data.xml")
public class HibTest {
@PersistenceContext
protected EntityManager em;
protected Session session;
@Before
public void dbAllSet() {
session = em.unwrap(Session.class);
}
@Test
@Commit
public void mergeCollections() {
Client client = session.get(Client.class, 100); // with accounts: 10, 11
List<Account> newUpdatedListAccount = newUpdatedListAccount();
client.getAccounts().clear();
client.getAccounts().addAll(newUpdatedListAccount);
session.saveOrUpdate(client);
session.flush();
Account account12 = session.get(Account.class, 12);
System.out.println(account12.getClient().getId()); // 101 nothing has changed, must be 100
}
private List<Account> newUpdatedListAccount() {
ArrayList<Account> accounts = new ArrayList<>();
accounts.add(session.get(Account.class, 12)); // new account from other client
accounts.add(session.get(Account.class, 10)); // existing account in updated client
return accounts;
}
}
但更新不起作用。并且更新不显示在sql日志中。 如何正确更新?这是一个非常常见的情况。
【问题讨论】:
-
您必须在 account12 中设置“客户端”。如果您获取 account12,它包含 ID 为 101 的
client。更好的模式是addAccount、removeAccount、clearAccounts函数,它在添加的 Account 中设置client。 -
@drkunibar 我不明白它是什么?它没有回答我的问题
-
我试图在回答中澄清我的评论。查看
Client中的addAccount方法和所有其他附加方法。我也更改了您的unit-test代码。
标签: spring hibernate spring-data-jpa hibernate-mapping spring-rest