Spring data jpa 实体类配置问题
使用Spring data jpa 时候实体类注意事项:
碰到问题:使用SysUserRepository自带的find方法查询不到数据,使用findall查询到的拘束,基本都是null,除了个别可以查询到。
解决:为实体类配置IdClass,即实体类需要有一个与数据库中的表完全对应的实体类,然后还需要有一个实体类作为IdClass,即建一个普通实体类,里面只包含表中的ID所对应的所有字段。网上查到的说法是:第一个为该接口处理的域对象类型,第二个为该域对象的主键类型。
如:
SysUser
public class SysUser {
@Id
@Column(name = "ACCOUNT_NO")
private String accountNo;
@Id
@Column(name = "USER_ID")
private String userId;
@Column(name = "USER_TYPE")
private String userType;
@Column(name = "USER_NAME")
public SysUser() {
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
SysUserId
public class SysUserId implements Serializable {
private String accountNo;
private String userId;
public SysUserId(){}
public SysUserId(String accountNo, String userId) {
this.accountNo = accountNo;
this.userId = userId;
}
public String getAccountNo() {
return accountNo;
}
public String getUserId() {
return userId;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "SysUserId{" +
"accountNo='" + accountNo + '\'' +
", userId='" + userId + '\'' +
'}';
}
}
@Repository
public interface SysUserRepository extends JpaRepository<SysUser, SysUserId> {
SysUser findByAccountNoAndUserId(@Param("ACCOUNT_NO") String accountNo, @Param("USER_ID") String userId);
}
需要注意的是在继承的JpaRepository里面的泛型,一个是对应表中的实体类,一个是ID对应的实体类。