I have the following classes:
@Entity
@Table(name = \"my_entity\")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyEntity {
@EmbeddedId
pr
Okay, I also tried doing this with @IdClass instead:
@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;
}
// Auto-generated by Eclipse.
@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;
}
// Auto-generated by Eclipse.
@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 did gave me a different error message, a NullPointerException, that was hinting to me that Spring Data JPA was unable to build the query for findAllByUserId(...). I made a custom implementation of that query method instead:
public interface MyEntityRepository extends JpaRepository, MyEntityRepositoryCustom {
}
public interface MyEntityRepositoryCustom {
List findAllByUserId(String userId);
}
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List findAllByUserId(String userId) {
return em
.createQuery("select o from MyEntity o where o.userId=:userId",
MyEntity.class).setParameter("userId", userId).getResultList();
}
}
...and voilá, it works!