栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何查询复合主键的子集?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何查询复合主键的子集?

好的,我还尝试使用以下方法执行此操作

@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;    }    // 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;    }}

这确实给了我一个不同的错误消息a

NullPointerException
,这向我暗示Spring Data
JPA无法为构建查询
findAllByUserId(...)
。我改为对该查询方法进行了自定义实现:

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();    }}

…而且, 它起作用了!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号