I am new to spring boot. I am trying to do some examples to learn.
我是新来的。我试着做一些例子来学习。
I have 2 entitles user "profile" and "address".
profile can have many addresses.
我有2个授权用户“个人资料”和“地址”。配置文件可以有多个地址。
public class Address {
@Id
private UUID id;
private boolean primaryAddress;
}
and the profile
而这份档案
@Entity
public class UserProfile {
@Id
private UUID id;
@OneToMany(
fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.REMOVE
)
@JoinColumn(
name = "profile_id",
foreignKey = @ForeignKey(name = "fk_address_userprofile")
)
private Set<Address> addressList = new HashSet<>();
}
when the user enter an address and if it is the primary address, i need to set primaryAddress field of all the other address of this user to false
当用户输入地址并且如果它是主要地址时,我需要将该用户的所有其他地址的PrimiyAddress字段设置为False
The problem I have is in my address repository how to write this query. I tried the native query but it does not seems to work.
我遇到的问题是在我的地址存储库中如何编写这个查询。我尝试了原生查询,但似乎不起作用。
@Repository
public interface AddressRepository extends JpaRepository<Address, UUID> {
@Modifying
//@Query(value = "UPDATE Address SET primary_address = false WHERE profile_id = ?1", nativeQuery = true)
@Query("UPDATE Address SET primaryAddress=false where UserProfile.id = ?1 ")
void resetPrimaryByUserProfileId(UUID userProfileId);
}
can anyone provide some help on how to do this?
有人能就如何做到这一点提供一些帮助吗?
更多回答
优秀答案推荐
The point of using ORM is allow us to use the OOP technique to update the DB tables. So you can think it with OOP mindset , just update the required Address
object to the correct state and hibernate will figure out what is the update SQL , but not writing the update SQL by yourself.
使用ORM的目的是允许我们使用面向对象技术来更新数据库表。因此,您可以按照面向对象的思维方式来思考,只需将所需的Address对象更新到正确的状态,Hibernate就会找出什么是更新SQL,而不是自己编写更新SQL。
You can do something likes :
你可以做一些类似的事情:
@Entity
public class UserProfile {
public void addAddress(Address addr){
if(addr.primaryAddress){
addressList.forEach(addr->addr.setPrimaryAddress(false));
}
addressList.add(addr);
}
}
UserProfile userProfile = userProfileRepository.getById(1);
userPrfile.addAddress(someAddress);
By the way , I have the following code review comments for your reference :
顺便提一下,我有以下代码审查意见供您参考:
FetchType.EAGER
is a bad idea.
- Mapping one-to-many as the bi-directional may be more efficient .
更多回答
我是一名优秀的程序员,十分优秀!