簡體   English   中英

JPA delete 在后台執行更新查詢

[英]JPA delete executes update query in the background

我正在嘗試使用JpaRepository.deleteById()從數據庫中刪除我的 JPA 實體,但我收到一個奇怪的錯誤:

NULL not allowed for column "USER_ID"; SQL statement:
update event set from_date=?, name=?, user_id=?, until_date=? where id=? [23502-199]

如您所見,它執行UPDATE查詢,但我不知道為什么。

我的模型看起來像這樣

@Entity
@Data
@NoArgsConstructor
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)
    private User organizer;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date fromDate;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date untilDate;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "event_allowed_users",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id"))
    private List<User> allowedUsers;
}
@Data
@Entity
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String user;

    @Column(unique = true)
    private String mail;

    private boolean active;
}

我也有自己的 SQL 模式查詢

create table user (id bigint NOT NULL AUTO_INCREMENT, active boolean not null, mail varchar(255) not null unique, user varchar(255), primary key (id));

create table event (id bigint NOT NULL AUTO_INCREMENT, name varchar(255), from_date timestamp not null, until_date timestamp not null, user_id bigint not null, primary key (id));

alter table event add constraint fk_user_id1 foreign key (user_id) references user(id);

create table event_allowed_users (event_id bigint, user_id bigint, foreign key (event_id) references event(id) on delete cascade, foreign key (user_id) references user(id) on delete cascade);

知道我在哪里犯了錯誤嗎?

我已經解決了這個問題,但不是ORM方式。

我使用本機查詢來刪除事件,它就像一個魅力。 它刪除事件以及 ManyToMany 關系表。

我的服務看起來像這樣:

@Resource
    private EventRepository eventRepository;

@Transactional
public void deleteEvent(Long id) {
    eventRepository.customDelete(id);
}

我不得不添加@Transactional,因為需要在事務中執行 DELETE 操作。

這是存儲庫本機查詢:

@Modifying
@Query(value = "DELETE FROM event WHERE id = ?1", nativeQuery = true)
    void customDelete(Long id);

使用 INSERT、UPDATE、DELETE 時,您需要使用@Modifying進行查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM