我似乎通过覆盖保存方法来解决它,我确信有更好的方法,我愿意接受建议。
基础存储库
@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)
}
联系存储库
@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 中有一种烘焙方式可以使用注释来做这种事情,而不必推出这样的解决方案,我只是不想过度这样做。我通过文档和在线搜索,但没有找到解决方案。我可能忽略了一些东西,不确定。