Reputation: 1055
I'd like to use jpa repository with specification
now I have two tables
@Entity
@Table(name="user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long idUser;
private Area area;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="idarea")
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
and Area Table
@Entity
@Table(name = "area")
public class Area {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
}
Then I have user Repository that extens also JpaSpecificationExecutor
public interface UserRepository extends CrudRepository<User,Long>,JpaSpecificationExecutor<User> {
}
Finally I have a simple specification
public class UserSpecification {
public static Specification<User> findByAreaName(final String areaName){
return new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root,
CriteriaQuery<?> criteria, CriteriaBuilder cb) {
return cb.equal(root.<String>get("??????"),areaName);
}
};
}
}
So, my question is :What I have to put in "?????" that is the areaName of table area?
Upvotes: 4
Views: 4793
Reputation: 4094
You could try
return cb.equal((Path<String>) ((Path<Area>) root.get("area")).get("areaName"),areaName);
And you have to make sure, that Area gets loaded, because its lazy.
Edit: As I mentioned in my comment, maybe just try without casting at all.
I have a method for such cases you can adjust for your needs:
@SuppressWarnings("unchecked")
private <T, R> Path<R> getPath(Class<R> resultType, Path<T> root, String path) {
String[] pathElements = path.split("\\.");
Path<?> retVal = root;
for (String pathEl : pathElements) {
retVal = (Path<R>) retVal.get(pathEl);
}
return (Path<R>) retVal;
}
Its called with the dot-notation to get the path. In your case it would be:
getPath(String.class, root, "area.areaName");
Hope it helps!
Upvotes: 8