我似乎通過覆蓋保存方法來解決它,我確信有更好的方法,我願意接受建議。
BaseRepository
@NoRepositoryBean
interface BaseRepository<T, ID extends Serializable> extends Repository<T, Long> {
@RestResource(path="byIdIn",rel="byIdIn")
@Query("select r from #{#entityName} r where r.id in :q")
Page<T> findByIdIn(@Param("q") List<Long> q, Pageable pageable)
Page<T> findAll(Pageable pageable)
T findOne(ID id)
T save(T entity)
T delete(ID id)
}
ContactRepository
@RepositoryRestResource(collectionResourceRel="contacts", path="contacts")
interface ContactRepository extends BaseRepository<Contact, Long>, ContactRepositoryCustom {
}
ContactRepositoryCustom
interface ContactRepositoryCustom {
public <S extends Contact> S save(S entity)
}
ContactRepositoryImpl
@NoRepositoryBean
class ContactRepositoryImpl implements ContactRepositoryCustom {
@PersistenceContext
private EntityManager em
@Transactional
@Override
public <S extends Contact> S save(S entity) {
Contact contact = entity as Contact
try {
em.persist(contact)
contact.getComment().each {
Comment comment = new Comment(contact, it)
em.persist(comment)
}
} catch (Exception e) {
println e
}
return contact
}
}
這只是一個示例,它需要一些清理,但我有save()方法按預期工作。如果在Spring Data/Spring Data Rest中有一個烘焙的方法,而不需要像這樣推出解決方案,那麼我就不想這樣做。我搜索了文檔和在線,但沒有找到解決方案。我可能忽略了一些東西,不確定。
我想你需要一個標準的Spring MVC控制器在這種情況下:http://stackoverflow.com/questions/40362789/how-to-save-many-objects-in-the-same-request-using-spring-引導數據休息 –