WeiPong
V2EX  ›  Java

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

  •  
  •   WeiPong · Jul 11, 2019 · 4514 views
    This topic created in 2673 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
    nutting
    Jul 11, 2019
    1
    得以操作 Area 为准吧
    auin
    auin
    Jul 11, 2019
    2
    用 aRepository.getOne(id) 获取个代理对象,放到 Pod 对象的 a 属性中,最后 save(pod)
    adzchao
    adzchao
    Jul 11, 2019
    3
    同楼上
    WeiPong
    WeiPong
    OP
    Jul 11, 2019
    4
    @liuxey
    @adzchao
    是的,昨晚最后也是做了这样的操作成了,还没弄太明白这样子的原理,今天有时间得好好研究下。
    EastLord
    EastLord
    Jul 25, 2019
    5
    Area a = new Area();
    a.setId(xxx);

    p.setArea(a);

    aRepository.save(a);
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2559 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:49 · PVG 22:49 · LAX 06:49 · JFK 09:49
    ♥ Do have faith in what you're doing.