【问题标题】:Q: JPA save() save other object问:JPA save() 保存其他对象
【发布时间】:2019-04-10 00:11:12
【问题描述】:

我想知道 JAP Repotitoty 的详细信息。 我创建了一个服务类、实体类和存储库类,如下所示(用 kotlin 编写)并执行了 ItemService#update 方法。

在执行 item2Repository 的 save() 方法时, item1 和 item2 都被更新了。

@Service
class ItemService(@Autowired private val item1Repository: Item1Repository, @Autowired private val item2Repository: Item2Repository) {

    fun update(id: Long) {

        val item1 = item1Repository.findById(1).get()
        item1.name = "updated!"

        val item2 = item2Repository.findById(1).get()
        item2.name = "updated!"

        // item1 and item2 were updated.
        item2Repository.save(item2)
    }
}


@Entity
@Table(name = "item1")
data class Item1(

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long = 0,

        @Column
        var name: String = ""
)    

@Entity
@Table(name = "item2")
data class Item2(

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long = 0,

        @Column
        var name: String = ""
)

interface Item1Repository: JpaRepository<Item1, Long>

interface Item2Repository: JpaRepository<Item2, Long>

为什么要更新 item1? 我认为执行 findById 方法时 item1 和 item2 都在持久性上下文中进行管理。 当我执行 jpa 存储库的 save 方法时,是否会保存持久性上下文中存在的所有对象?

【问题讨论】:

    标签: java spring jpa kotlin spring-data-jpa


    【解决方案1】:

    由于它是“托管”实例,您不必调用save 来保存它 - 对托管实例所做的所有更改都会反映在数据库中。 为了防止这种行为,您必须分离该实例,使其表现得像 POJO 而不是代理。

    保存用于persist 新实体或merge 分离。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2011-08-21
      • 2019-12-29
      • 2012-11-07
      • 2021-03-13
      • 2018-04-26
      • 2018-02-24
      相关资源
      最近更新 更多