亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

外鍵正在更新為空

外鍵正在更新為空

白豬掌柜的 2023-10-13 10:06:55
我正在嘗試使用 @OneToMany 和 @ManyToOne JPA 注釋實現雙向關系。我的外鍵被更新為 NULL,這是不正確的。我需要一些意見來解決這個問題。我創建了 User 和 CardInfo 類。我正在嘗試添加一種關系,其中用戶可以擁有多張卡。當我嘗試保留數據庫時,外鍵被插入為空。@Entity@Table(name = "customer_info")@Data@NoArgsConstructor@AllArgsConstructorpublic 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。如果理解不正確請指正。
查看完整描述

1 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

盡管Cascade.PERSIST確保CardInfo對象與其父對象一起持久存在User,但維護關系是應用程序或對象模型的責任[ 1 ]。


由于外鍵位于 中CardInfo,因此您必須確保每個都CardInfo與您要保留的 相關聯User。一種常見的模式是添加額外的邏輯來處理域對象中關系的雙方,例如:


public class User {


    // fields, accessors and mutators


    public void addPaymentDetails(CardInfo cardInfo) {

        if (paymentDetails == null) {

            paymentDetails = new LinkedHashSet<>();

        }

        if (cardInfo.getUser() != this) {

            cardInfo.setUser(this);

        }

        paymentDetails.add(cardInfo);

    }


}

上面的代碼確保關系的雙方同步(即,如果用戶將卡添加到其付款詳細信息中,則該卡信息由用戶“擁有”)。


CardInfo最后,雖然與您的問題沒有直接關系,但我的建議是在和 之間建立強制關系User及其各自的連接列,NOT NULL以便查詢得到正確優化,并且CardInfo數據庫中不能存在與其所屬的關聯User:


@ManyToOne(fetch = FetchType.LAZY, optional = false)

@JoinColumn(name="user_id", nullable = false)


查看完整回答
反對 回復 2023-10-13
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號