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<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;
	}
}

  

_

猜你喜欢

转载自www.cnblogs.com/luohaonan/p/11252068.html
今日推荐