Spring Data Jpa自定义关联查询

Spring Data Jpa自定义关联查询,可以使用原生SQL,也可以使用JPQL语法。
原生SQL返回数组对象List<Object[]>;JPQL返回自定义对象List

ViewUserInfo.java

/**
 * 自定义实体
 */
public class ViewUserInfo {
	//table: user info
	private Integer id;
    private String name;
    private String username;
    //table: role
    private long roleId;
    //table: permission
    private String url;
    private String permission; 
    
    public ViewUserInfo(){
    }
    
    public ViewUserInfo(int userId,String username,String name,
    				long roleid,String url,String permission){
    	this.id=userId;
    	this.username=username;
    	this.name=name;
    	this.roleId= roleid;
    	this.url=url;
    	this.permission=permission;
    }    
	
	set,get...

}

JpaUserRepository.java

//查询方法定义 SQL
@Query(value = "select "
+" a.id as userId,a.username,a.name,b.role_id as roleId,d.url,d.permission "
+" from user_info a, sys_user_role b, sys_role_permission c,sys_permission d "
+" where a.id=b.u_id and b.role_id=c.role_id and c.permission_id=d.id",
	nativeQuery = true)//原生SQL
public List<Object[]> findByNameSQL(String name);
//查询方法定义 JPQL
@Query(value = "select new com.test.demo.model.ViewUserInfo("
+" a.id,a.username,a.name,b.roleid,c.url,c.permission ) "
+" from JpaUser a, SysUserRole b, SysPermission c "
+" where a.id=b.uid and b.roleid=c.id")
public List<ViewUserInfo> findByName(String name);

JpaController.java

//原生SQL
@RequestMapping("/jpa/getSql")
public String getNameSql(@RequestParam String name) {
	List<Object[]> users = userRepository.findByNameSQL(name);
	for(Object[] objs : users){
		System.out.println("----");
		for(int i = 0,j=objs.length; i < j; i++){
			System.out.println("--"+objs[i]);
		}
	}
	return "/";
}
//JPQL
@RequestMapping("/jpa/getJpql")
public String getName(@RequestParam String name) {
	List<ViewUserInfo> users = userRepository.findByName(name);
	for(ViewUserInfo user : users){
		System.out.println("----");
		System.out.println("----"+user.getName());
		System.out.println("----"+user.getUrl());
	}
	return "/";
}

JPQL自定义语法中的对象是对应每个表的JOPO,不再逐一罗列
SysUserRole.java

@Entity
@Table(name = "sys_user_role")
public class SysUserRole {
	@Id
	private Integer id;
	@Column(name="role_id")
	private Long roleid;
	@Column(name="u_id")
	private Long uid;
	
	get,set...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值