gpt4 book ai didi

java - Spring 数据 JPA "ON DUPLICATE KEY UPDATE amount = account.amount + someValue"

转载 作者:行者123 更新时间:2023-12-05 05:55:44 26 4
gpt4 key购买 nike

假设我有下一个实体

@Entity
@Table(name = "account")
public class Account {

@Id
private long id;

private long amount;

}

我想为现有值添加一些值并在数据库中更新它或者,如果此帐户尚不存在,我想创建一个新帐户。

Spring Data JPA 的基本方法是:

 var account = dataJpaRepository.findById(id);
if (account==null) {account = new Account(id,someValue}
else {account.set(account.getAmount() + someValue);}
dataJpaRepository.save(account);

在这种情况下,完成了对数据库的两个请求,但是使用 native 查询我可以通过发送一个请求来完成,例如:

"INSERT INTO account (id, amount) VALUES (:id, someValue) ON DUPLICATE KEY UPDATE 
amount = account.amount + someValue"

是否可以通过 Spring Data JPA/JPQL 来做同样的事情并减少请求量?

最佳答案

绝对不确定这是否有效,但您可以尝试两件事:

@Repository
public interface AccountRepo extends JpaRepository<Account, Long> {
// First try
@Query(native = "INSERT INTO account (id, amount) VALUES (:id, :someValue) ON DUPLICATE KEY UPDATE amount = account.amount + :someValue")
Long addAmount(@Param("id") Long id, @Param("someValue") Long amount);

// Second try
default Account addAmount(Long id, Long amount) {
findById(id).map(a -> {a.amount += amount; return a;}).ifPresentOrElse(a -> save(a), () -> {return save(new Account(amount));})
}

}

关于java - Spring 数据 JPA "ON DUPLICATE KEY UPDATE amount = account.amount + someValue",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69373529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com