gpt4 book ai didi

java - Spring Boot,如何在具有 EmbeddedId 的表中插入新记录

转载 作者:行者123 更新时间:2023-12-01 22:41:37 24 4
gpt4 key购买 nike

我是 Spring-boot 的新手,但对 JPA 有点熟悉。我正在处理一个项目,我已经设置了数据库并从数据库生成了模型。我至少参与过 4 个 JPA 项目,这是我第一次遇到 @EmbeddedId

我有一张Passenger表,看起来像

public class Passenger implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PassengerPK passengerPK;
@Size(max = 13)
@JoinColumn(name = "user_uuid", referencedColumnName = "uuid", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private User user;
@Column(name = "date_created")
@Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
....
}

以及我生成的passengerPK

@Embeddable
public class PassengerPK implements Serializable {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "uuid")
private String uuid;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "user_uuid")
private String userUuid;

public PassengerPK() {
}
...
}

如果 JPA 中没有 @EmbeddedId,我会首先初始化 将新记录添加到 Passenger 表中并保存用户

final User user = new User();
user.setUuid(UUID.randomUUID().toString());
user.setFname(passengerDto.getFirstName());
user.setLname(passengerDto.getLastName());
user.setPassword(passwordEncoder.encode(passengerDto.getPassword()));
user.setEmail(passengerDto.getEmail());
user.setPhone(passengerDto.getPhone());
user.setDateCreated(new Date());

User savedUser = userRepository.save(user);

然后将该用户传递给我的新 Passenger,例如

  final Passenger passenger = new Passenger();
passenger.setUuid(UUID.randomUUID().toString());
passenger.setUser(savedUser);
passenger.setDateCreated(new Date());
Passenger savedPassenger = passengerRepository.save(passenger);

But this fails, I get an error that `user_uuid` is null

然后我改变尝试类似的事情

final Passenger passenger = new Passenger();
PassengerPK passengerPK = new PassengerPK();
passengerPK.setUuid(UUID.randomUUID().toString());
passengerPK.setUserUuid(savedUser.getUuid());
passenger.setPassengerPK(passengerPK);
passenger.setDateCreated(new Date());
Passenger savedPassenger = passengerRepository.save(passenger);

我收到错误java.sql.SQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(mydatabase.passenger,CONSTRAINT fk_passenger_user1外键(user_uuid)引用user(uuid)删除时无操作更新时无操作)有人可以帮我理解这一点吗?

最佳答案

事实证明,我的 user 表存储引擎是 myISAM,而不是像我的其他表一样的 innoDB。我将其更改为 innoDB 并且我的代码有效。

关于java - Spring Boot,如何在具有 EmbeddedId 的表中插入新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491339/

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