WeiPong
V2EX  ›  Java

请教个关于 JPA 级联保存的问题

  •  
  •   WeiPong · Jul 11, 2019 · 4266 views
  •   You need to sign in to view this topic
    This topic created in 2589 days ago, the information mentioned may be changed or developed.

    请教各位大佬关于 JPA 的问题,有点菜,几个小时没想出来怎么做,搜索信息也没找到相关的解决方法。

    两张表,一张货架区域表 Area (一端),一张货架表 Pod (多端)。

    Pod 中的 area 设置 @ManyToOne 对应 areaid,设置及联 cascadeType 后,保存时,如果区域表中已存在 A 区域,货架 P1 的区域为区域 A,接着添加或者更新货架 P2 的区域同样没为 A 区域的话,数据库中会有两条 ID 不用,属性一样的区域 A 信息。

    怎么才能实现不会添加第二条区域 A 的信息,直接给 P2 的区域信息设置为已有的区域 A 呢?

    5 replies    2019-07-25 16:16:34 +08:00
    nutting
        1
    nutting  
       Jul 11, 2019
    得以操作 Area 为准吧
    auin
        2
    auin  
       Jul 11, 2019
    用 aRepository.getOne(id) 获取个代理对象,放到 Pod 对象的 a 属性中,最后 save(pod)
    adzchao
        3
    adzchao  
       Jul 11, 2019
    同楼上
    WeiPong
        4
    WeiPong  
    OP
       Jul 11, 2019
    @liuxey
    @adzchao
    是的,昨晚最后也是做了这样的操作成了,还没弄太明白这样子的原理,今天有时间得好好研究下。
    EastLord
        5
    EastLord  
       Jul 25, 2019
    Area a = new Area();
    a.setId(xxx);

    p.setArea(a);

    aRepository.save(a);
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3504 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:48 · PVG 12:48 · LAX 21:48 · JFK 00:48
    ♥ Do have faith in what you're doing.