我一直试图在spring-data-jpa中使用额外列实现@ManyToMany关系。
正如这篇文章https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-hsql/ 但不幸的是,它并不适用于我的情况。
以下是我的课程:
@Entity
public class AccountEvent implements Serializable {
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "event_id")
private Event event;
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "account_id")
private Account account;
@Column(name = "is_confirmed", nullable = false)
private boolean isConfirmed;
public AccountEvent() {
}
public AccountEvent(Event event, Account account) {
this.event = event;
this.account = account;
this.isConfirmed = false;
}
public AccountEvent(Event event, Account account, boolean isConfirmed) {
this.event = event;
this.account = account;
this.isConfirmed = isConfirmed;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public boolean isConfirmed() {
return isConfirmed;
}
public void setConfirmed(boolean confirmed) {
isConfirmed = confirmed;
}
}
帐户权利
@Entity
public class Account {
@Id
@Column(name = "id", updatable = false, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
@SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq", allocationSize = 1)
private Long id;
[...]
@OneToMany(mappedBy = "account")
private Set<AccountEvent> accountEvents;
}
事件实体
@Entity
public class Event implements Serializable {
@Id
@NotNull
@Column(name = "id", updatable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "event_id_seq")
@SequenceGenerator(name = "event_id_seq", sequenceName = "event_id_seq", allocationSize = 1)
private Long id;
[...]
@OneToMany(mappedBy = "event", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<AccountEvent> accountEvents;
}
我试图保留这些数据的方法。
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void signUpForAnEvent(String login, Event event) throws AppException {
Account account = accountRepository.findByLogin(login);
AccountEvent accountEvent = new AccountEvent(event, account);
event.getAccountEvents().add(accountEvent);
logger.info("Signing up user: " + account.toString() + " , for event: " + event.toString());
eventRepository.save(event);
}
每当我尝试坚持(保存方法)数据时,我都会收到这样的异常
org.postgresql.util.PSQLException: ERROR: null value in column "event_id" violates not-null constraint
Szczegóły: Failing row contains (f, null, null).
我做错了什么?