JPA#复杂查询#自定义查询

本文介绍如何在SpringDataJPA中实现自定义SQL查询。通过创建自定义接口和实现类,可以灵活地执行复杂的SQL语句,示例展示了如何编写自定义SQL并返回查询结果。

编写自定义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<StudentVO> 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<StudentVO> 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;
	}
}

  

 

 

_

转载于:https://www.cnblogs.com/luohaonan/p/11252068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值