我似乎通过覆盖保存方法来解决它,我确信有更好的方法,我愿意接受建议。
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-引导数据休息 –