自定义aop实现jpa命名查询_JPA#复杂查询#自定义查询

编写自定义SQL基于下面信息:

1. SpringData JPA 在为Repository接口生成实现的时候,会查找是否有 "接口名称"+"Impl"的类,如果有的话,就把这个类的方法合并到要生成的实现当中。

-----

假设:要为接口StudentRepository编写自定义sql查询。

基于最前面的信息,要编写自定义SQL,需要下面三步:

1. 自定义一个接口,在在接口中声明方法StudentCoustomRepository,这个自定义接口名称不重要;

2. 让目标接口继承自定义接口,这样目标接口就有了相应的方法;

3. 编写自定义方法的实现类,这个类需要使用"目标接口名称"+"Impl"为类名,

即StudentRepositoryImpl,这样SpringDataJpa 为StudentRepository生成实现的时候就会包含这里面的方法了。

----

public class StudentRepositoryImpl implements StudentCoustomRepository {

// 这里可以写很复杂的SQL,作为演示之用,就不弄那么复杂

private static final String SQL = "select * from t_student where name like :name ";

@PersistenceContext

private EntityManager em;

@SuppressWarnings({ "rawtypes", "unchecked" })

@Override

public List findByName(String name) {

Query query = em.createNativeQuery(SQL).setParameter("name", "%"+name+"%");

query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

List queryList = query.getResultList();

if (queryList.size() == 0) {

System.out.println("找不到Student name为" + name + "的记录");

return null;

}

List retVal = new ArrayList<>();

for(Object o : queryList) {

Map student = (Map)o;

StudentVO vo = new StudentVO();

try {

// org.apache.commons.beanutils.BeanUtils;

// 使用apaches的beanutil,直接吧map转为实例

BeanUtils.populate(vo, student);

retVal.add(vo);

} catch (IllegalAccessException | InvocationTargetException e) {

System.out.println("解析StudentVO bean时发生异常:" + e.getMessage());

}

}

return retVal;

}

}

_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值