问题描述
我正在将 Spring Boot 应用程序迁移到 micronaut,并偶然发现了 micronaut 数据的问题。 使用在 Spring Boot 数据中工作的本机查询时,我尝试将一些数据插入关联表的查询出现编译错误。
Unable to implement Repository method: MyEntityRepository.insertQueryExample(int id,String name). No possible implementations found.
其他原生查询(选择、删除)没有问题,生成的方法也是如此。 使用上述方法的 repo 如下所示:
public interface MyEntityRepository extends CrudRepository<MyEntity,Integer> {
@Query(value = "insert into my_entity_my_entity2 (id,id2)" +
" values (:id,(select me2.id from my_entity2 os where me2.name = :name))",nativeQuery = true)
void insertQueryExample(int id,String name);
}
my_entity_my_entity2 没有实体类,但它在春季有效,所以我认为这不是问题。
预先感谢您的帮助。
解决方法
my_entity_my_entity2 没有实体类,但它在春季有效,所以我认为这不是问题。
确实,这就是问题所在。
All io.micronaut.data.repository.GenericRepository
期望各自的实体类型(必须自省,它是 Micronaut Data JPA 还是 Micronaut Data JDBC 实现。
剩下的解决方案是实现自定义 JpaRepository
子类型并使用注入的 EntityManager
或 JpaRepositoryOperations
来执行自定义查询执行,同时保留默认拦截方法:
@Repository
public abstract class MyEntityRepository implements CrudRepository < MyEntity,Integer> {
@Inject
JpaRepositoryOperations operations;
@Transactional
void insertQueryExample(int id,String name) {
operations.getCurrentEntityManager()
.createNativeQuery("insert into my_entity_my_entity2 (id,id2)" +
" values (:id,(select os.id from my_entity2 os where os.name = :name))")
.setParameter("id",id)
.setParameter("name",name)
.executeUpdate();
}
}
然后您可以注入您的 MyEntityRepository
bean 并调用您的自定义查询方法。