在jpa的JpaRepository需要对符合主键@EmbeddedId 中的一个字段进行查询的用法:
在JpaRepository Interface中使用findByIdRoleId 这样的语法。jpa会自动生成正确的sql语句。
例子:
1.pojo 类
RoleMenu.java
package com.ninelephas.whale.pojo;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* The persistent class for the role_menu database table.
*
*/
@Entity
@Table(name="role_menu")
@NamedQuery(name="RoleMenu.findAll", query="SELECT r FROM RoleMenu r")
public class RoleMenu implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private RoleMenuPK id;
@Column(name="created_by")
private String createdBy;
。。。
}
2.复合组件类
RoleMenuPK.javapackage com.ninelephas.whale.pojo;
import java.io.Serializable;
import javax.persistence.*;
/**
* The primary key class for the role_menu database table.
*
*/
@Embeddable
public class RoleMenuPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="menu_id")
private String menuId;
@Column(name="role_id")
private String roleId;
public RoleMenuPK() {
}
public String getMenuId() {
return this.menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getRoleId() {
return this.roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof RoleMenuPK)) {
return false;
}
RoleMenuPK castOther = (RoleMenuPK)other;
return
this.menuId.equals(castOther.menuId)
&& this.roleId.equals(castOther.roleId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.menuId.hashCode();
hash = hash * prime + this.roleId.hashCode();
return hash;
}
}
3.JpaRepository 继承接口
@Repository("com.ninelephas.whale.repository.IRoleMenuRepository")
public interface IRoleMenuRepository extends JpaRepository<RoleMenu, RoleMenuPK>, PagingAndSortingRepository<RoleMenu, RoleMenuPK> {
public List<RoleMenu> findByIdRoleId(String roleId);
}
JpaRepository只要定义
public List<RoleMenu> findByIdRoleId(String roleId);
Id - is the @EmbeddedId in RoleMenu.
RoleId is an attribute within RoleMenuPK
这样jpa就会自动生成对role_menu中的复合主键中的role_id 进行查询的sql语句
---------------------
作者:remote_roamer
来源:CSDN
原文:https://blog.csdn.net/remote_roamer/article/details/52706196
版权声明:本文为博主原创文章,转载请附上博文链接!