質問

私持っている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;

}

Iは、AオブジェクトにBオブジェクトを追加するメソッドを有します。私は、新しく追加された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?


}
役に立ちましたか?

解決

  

Iは、AオブジェクトにBオブジェクトを追加するメソッドを有します。私は、新しく追加された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());
}
ところで、あなたのコードは、ビット厄介である、あなたはEMとのそれぞれの相互作用の後commitする必要はありません。

他のヒント

私は受け入れ答えが正しいとは思いません。 https://coderanch.com/t/628230/frameworkを参照してください。 /春-DATA-得る-ID付加する

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ありCommentRepositoryAutowired

与えられたTODO IDを持つ新しいコメントを関連付けるためにPOSTの/api/todos/1/commentsを受信することが可能な残りのエンドポイントが与えられます。

    @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...
    }

あなたは、そのコンテナに追加し、最初に新しく作成したオブジェクトを永続化する必要があります。 Additionaly、saveorg.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
誰かが前のコメントの解決策を見つけられない場合は、別のオプションを追加することです。

@GeneratedValue(strategy = yourChosenStrategy)

エンティティのIDの上に、あなたは、持続(またはそのゲッターオーバー)されています。持続が呼び出されたときに、この場合には、IDが自動的に永続オブジェクトに設定されます。

希望、それが役立ちます!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top