Ok, I also tried to do this with @IdClass
:
@Entity
@Table(name = "my_entity")
@JsonIgnoreProperties(ignoreUnknown = true)
@IdClass(Pk.class)
public class MyEntity {
@Id private Integer type;
@Id private String userId;
public Pk getId() {
return id;
}
public void setId(Pk id) {
this.id = id;
}
}
@IdClass(Pk.class)
public class Pk implements Serializable {
private static final long serialVersionUID = -3090221844117493661L;
private Integer type;
private String userId;
public Pk() {
}
public Pk(String userId, Integer type) {
this.setUserId(userId);
this.setType(type);
}
public Integer getType() {
return type;
}
public String getUserId() {
return userId;
}
public void setType(Integer type) {
this.type = type;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pk other = (Pk) obj;
if (type != other.type)
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
}
This gave me another error message: NullPointerException
which hinted to me that Spring Data JPA could not build the query for findAllByUserId(...)
. Instead, I made my own implementation of this request method:
public interface MyEntityRepository extends JpaRepository<MyEntity, Pk>, MyEntityRepositoryCustom {
}
public interface MyEntityRepositoryCustom {
List<MyEntity> findAllByUserId(String userId);
}
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List<MyEntityRepositoryCustom> findAllByUserId(String userId) {
return em
.createQuery("select o from MyEntity o where o.userId=:userId",
MyEntity.class).setParameter("userId", userId).getResultList();
}
}
... voilá, !