4

次のような 2 つのエンティティ クラス A と B があります。

public class A{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;    

    @OneToMany(mappedBy = "a", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private List<B> blist = new ArrayList<B>();

    //Other class members;

}

クラス B:

public class B{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private A a;

    //Other class members;

}

B オブジェクトを A オブジェクトに追加するメソッドがあります。新しく追加された B オブジェクトの ID を返したい。

例えば:

public Long addBtoA(long aID){

            EntityTransaction tx = myDAO.getEntityManagerTransaction();

            tx.begin();
            A aObject = myDAO.load(aID);
            tx.commit();

            B bObject = new B();

            bObject.addB(bObject);

            tx.begin();
            myDAO.save(aObject);
            tx.commit();

            //Here I want to return the ID of the saved bObject.
            // After saving  aObject it's list of B objects has the newly added bObject with it's id. 
            // What is the best way to get its id?


}
4

4 に答える 4

4

受け入れられた答えが正しいとは思いません。https://coderanch.com/t/628230/framework/Spring-Data-obtain-id-addedを参照してください

tldr; 子のリポジトリを作成して、子Bを親から完全に独立して保存できるようにする必要があります。を保存したら、B entityそれを親に関連付けAます。

Todo親でありComment、子であるサンプルコードを次に示します。

@Entity
public class Todo {

    @OneToMany(mappedBy = "todo", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private Set<Comment> comments = new HashSet<>();

    // getters/setters omitted.
}

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "todo_id")
    private Todo todo;

    // getters/setters omitted.
}

これが春のデータでモデル化された場合、2 つのリポジトリを作成します。TodoRepositoryそしてCommentRepositoryどれが入っていAutowiredます。

POST/api/todos/1/commentsを受信して​​新しいコメントを特定の todo ID に関連付けることができる残りのエンドポイントを指定します。

    @PostMapping(value = "/api/todos/{todoId}/comments")
    public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
                                                      @RequestBody Comment comment) {

        Todo todo = todoRepository.findOne(todoId);

        // SAVE the comment first so its filled with the id from the DB.
        Comment savedComment = commentRepository.save(comment);

        // Associate the saved comment to the parent Todo.
        todo.addComment(savedComment);

        // Will update the comment with todo id FK.
        todoRepository.save(todo);

        // return payload...
    }

代わりに、以下を実行して、指定されたパラメーターを保存した場合comment。新しいコメントを取得する唯一の方法はtodo.getComments()commentコレクションがSet.

  @PostMapping(value = "/api/todos/{todoId}/comments")
    public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
                                                      @RequestBody Comment comment) {

        Todo todo = todoRepository.findOne(todoId);

        // Associate the supplied comment to the parent Todo.
        todo.addComment(comment);

        // Save the todo which will cascade the save into the child 
        // Comment table providing cascade on the parent is set 
        // to persist or all etc.
        Todo savedTodo = todoRepository.save(todo);

        // You cant do comment.getId
        // Hibernate creates a copy of comment and persists it or something.
        // The only way to get the new id is iterate through 
        // todo.getComments() and find the matching comment which is 
        // impractical especially if the collection is a set. 

        // return payload...
    }
于 2017-09-28T12:21:35.717 に答える
1

最初に新しく作成したオブジェクトを永続化してから、そのコンテナーに追加する必要があります。さらに、 のsaveメソッドはorg.hibernate.Session、新しく永続化されたオブジェクトの識別子を返します。したがって、次のように動作するようにコードおよび/または DAO を更新する必要があります。

newObject.setContainer(container); // facultative (only if the underlying SGBD forbids null references to the container)
Long id = (Long) hibernateSession.save(newObject); // assuming your identifier is a Long
container.add(newObject);
// now, id contains the id of your new object

とにかく、生成されたIDを持つすべてのオブジェクトに対して、いつでも次のようなことができます:

hibernateSession.persist(object); // persist returns void...
return object.getId(); // ... but you should have a getId method anyway
于 2010-08-09T11:25:28.217 に答える
1

B オブジェクトを A オブジェクトに追加するメソッドがあります。新しく追加された B オブジェクトの ID を返したい。

あとはやるだけ!新しい B インスタンスが永続化された (および変更されたインスタンスがデータベースにフラッシュされた) 後、そのインスタンスがid割り当てられます。それを返すだけです。この動作を示すテスト メソッドを次に示します。

@Test
public void test_Add_B_To_A() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPu");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();

    A a = em.find(A.class, 1L);

    B b = new B();
    A.addToBs(b); // convenient method that manages the bidirectional association

    em.getTransaction().commit(); // pending changes are flushed

    em.close();
    emf.close();

    assertNotNull(b.getId());
}

ところで、あなたのコードは少し乱雑ですcommit。EM とのやり取りのたびにそれを行う必要はありません。

于 2010-08-09T13:31:18.760 に答える
0

誰かが以前のコメントで解決策を見つけられない場合、別のオプションは追加することです

@GeneratedValue(strategy = yourChosenStrategy)

永続化しているエンティティの ID (またはそのゲッター) を介して)。この場合、persist が呼び出されると、id が永続オブジェクトに自動的に設定されます。

それが役に立てば幸い !

于 2013-07-19T09:46:06.730 に答える