如何避免Hibernate使用OneToMany为更新生成两个查询?

时间:2016-02-05 12:12:44

标签: java hibernate one-to-many hibernate-onetomany

我面临与this question相同的情况,没有有用的答案。

当我向一对多关系的许多部分添加一个新元素时,Hibernate会生成两个查询,一个用于插入,另一个用于将外键更新为父级。

为什么需要第二个查询?插入中是否设置了父级的id? 有没有办法避免这种情况?

    Hibernate:
        /* insert mydomain.LanguageKnowledge */
            insert
            into
                languageKnowledge
                (language_fk, level_fk, personId_fk)
            values
                (?, ?, ?)
    Hibernate:
        /* create one-to-many row mydomain.Person.offeredLanguages */
        update
            languageKnowledge
        set
            personId_fk=?
        where
            id=?



    public class LanguageKnowledge {

        @Id
        @GeneratedValue(strategy = IDENTITY)
        private Integer id;

        @Enumerated(STRING)
        @Column(name = "language_fk")
        private LanguageIso639_3 language;

        @Enumerated(STRING)
        @Column(name = "level_fk")
        private LanguageLevel level;

        protected LanguageKnowledge() {
        }
    }


    public class Person {

        @Id
        @GeneratedValue(strategy = IDENTITY)
        private Integer id;

        @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
        @JoinColumn(name = "personId_fk", referencedColumnName = "id", nullable = false)
        private final Set<LanguageKnowledge> offeredLanguages = new HashSet<>();

        public Person(Set<LanguageKnowledge> offeredLanguages) {
            addOfferedLanguages(offeredLanguages);
        }

        protected Person() {
        }

        public void addOfferedLanguages(Set<LanguageKnowledge> offeredLanguages) {
            this.offeredLanguages.addAll(offeredLanguages);
        }

        public void removeOfferedLanguages(Set<LanguageKnowledge> offeredLanguagesToRemove) {
            this.offeredLanguages.removeAll(offeredLanguagesToRemove);
        }
    }

1 个答案:

答案 0 :(得分:1)

该关联是单向的,因此Person是拥有方(因为它是唯一的一方)。

使关联成为双向关联,并使LanguageKnowledge成为关联所有者。这样您就可以避免冗余更新,因为外键值将被指定为LanguageKnowledge的插入语句的一部分。