简体   繁体   中英

Spring data jpa save

How can I pass the test? (was working before migrate my code to use repositories). The bs are stored in the database after save, but the object are not updated. What I have to do to achieve it?

Given these classes:

@Entity
public class A {
   @Id
   private String id;
   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinColumn(name = "aId")
   private Set<B> bs= new HashSet<B>();
   ...
}

@Entity
public class B {
   @Id
   @GeneratedValue
   private int id;
   private String aId;
   private String foo;
   ...
}

And Repository:

@RepositoryDefinition(domainClass = A.class, idClass = String.class)
public interface ARepository {
   ...
   void save(A a);
   ...
}

This test fail:

    // "a" saved and flushed
    B b = new B();
    b.setAId(a.getId());
    a.getBs().add(b);
    ARepository.save(a);
    assertTrue(b.getId() > 0);

repository.save() does persist (if the provided argument is transient) or merge (otherwise).

Since a is not transient, merge is performed, meaning that there is no persist operation that could be cascaded to bs .

You either have to save b explicitly or add b to a new a before the a is saved, so that persist is cascaded properly.

Probably, the reason is that B object is not in persisted state yet. As soon as it will be saved - you shouldn't get errors.

Should look like this:

// "a" saved and flushed
B b = new B();
BRepository.save(b)
b.setAId(a.getId());
a.getBs().add(b);
ARepository.save(a);
assertTrue(b.getId() > 0);

Also could you please provide stacktrace? Would be really helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM