我正在尝试使用 @OneToMany 和 @ManyToOne JPA 注释实现双向关系。我的外键被更新为 NULL,这是不正确的。我需要一些意见来解决这个问题。
我创建了 User 和 CardInfo 类。我正在尝试添加一种关系,其中用户可以拥有多张卡。当我尝试保留数据库时,外键被插入为空。
@Entity
@Table(name = "customer_info")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
//@GeneratedValue
private String userId;
private String userName;
private Date dateOfBirth;
private boolean primeMember;
@OneToMany(mappedBy = "user", cascade = CascadeType.PERSIST, orphanRemoval = true)
private Set<CardInfo> paymentDetails;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="card_info")
public class CardInfo implements Serializable {
@Id
private String cardNumber;
@Id
private String cardType; // Debit, Credit
private String cardCategory; // Visa, mastercard
private Date expiryDate;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
@EqualsAndHashCode.Include private User user;
public class DAOImpl {
@Transactional
public String addCustomer(User user) {
// User _user=new User();
// Set<CardInfo> cardData=new HashSet<>();
//
String userId=String.valueOf(Instant.now().toEpochMilli());
user.setUserId(userId);
Session session=sessionFactory.getCurrentSession();
session.persist(user);
return userId;
}
mysql> select * from card_info;
+----------+-------------+--------------+---------------------+---------+
| cardType | cardNumber | cardCategory | expiryDate | user_id |
+----------+-------------+--------------+---------------------+---------+
| CREDIT | 74959454959 | VISA | 2020-04-23 00:00:00 | NULL |
+----------+-------------+--------------+---------------------+---------+
1 row in set (0.00 sec)
user_id 列不应更新为 NULL。如果理解不正确请指正。
慕哥6287543
相关分类