使用JpaRepository更新和删除数据库

时间:2019-07-30 08:46:13

标签: java spring postgresql jpa spring-data-jpa

我有两个与ManyToMany关系相关的实体:

User.java

@Id
@Column(name = "user_id", updatable = false, nullable = false, unique = true)
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;

@Column(name = "name")
private String name;

@Column(name = "product")
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinTable(name = "products_users",
        joinColumns = {@JoinColumn(name = "user_id")},
        inverseJoinColumns = {@JoinColumn(name = "product_id")})
private Set<Product> products;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "created_on")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Date createdOn;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "modified_on")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Date modifiedOn;

// construuctors, getter, setter
}

产品.java

@Id
@Column(name = "product_id", updatable = false, nullable = false, unique = true)
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;

@Column(name = "name")
private String name;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "created_on")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Date createdOn;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "modified_on")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Date modifiedOn;

//getters, setters, contructors
}

我想由用户UUID从数据库中删除数据。我如何编写这样的查询

@Transactional
    @Modifying
    @Query(value = "delete from users where user_id = ?1", nativeQuery = true)
    void deleteByUUID(UUID uuid);

,但它将删除用户表中的唯一行。我希望删除有关该用户及其产品的所有数据。

而且我也不知道如何正确地更新用户及其产品。

2 个答案:

答案 0 :(得分:4)

关于级联,您已正确设置:

问题是您正在触发本机查询。这将完全绕开所有JPA配置和级联。即使您使用了不带本机的JPQL删除,这仍将忽略所有级联和JPA配置。

在代码中的某些地方,您需要使用findOne来获取用户。之后,使用delete方法。只有这样,级联才能起作用。

答案 1 :(得分:0)

基于Maciej Kowalski的答案

要在存储库中按UUID查找:

  Optional<User> findByUUID(UUID uuid);

要删除的服务:

Optional<User> optionalUser = repository.findByUUID(uuid);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            repository.delete(user);
        }
        // here on else you can throw an Exception

服务更新中:

Optional<User> optionalUser = repository.findByUUID(uuid);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            // Make changes here for example user.setName(otherName)
            repository.save(user);
        }
        // here on else you can throw an Exception
相关问题