如何查询复合主键的子集? [英] How to query on subset of composite primary key?

查看:106
本文介绍了如何查询复合主键的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  @Entity 
@Table(name =my_entity)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyEntity {
@EmbeddedId
private pk id;

public Pk getId(){
return id;
}

public void setId(Pk id){
this.id = id;
}

}

@Embeddable
public class Pk implements Serializable {
private static final long serialVersionUID = -3090221844117493661L;
私人整数类型;
private String userId;
$ b $ 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;
}

// 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());
返回结果;
}

// 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;
返回true;
}

}

公共接口MyEntityRepository扩展了JpaRepository< MyEntity,Pk> {

列表< MyEntity> findAllByUserId(String userId);

}

当我初始化Spring Data JPA时,

 线程main中的异常org.springframework.beans.factory.BeanCreationException:创建名为'myEntityRepository'的bean时出错:调用初始化方法失败;嵌套的异常是org.springframework.data.mapping.PropertyReferenceException:找不到类型为MyEntity的属性用户!在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)

在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
在org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject
(AbstractBeanFactory.java:296 )美元,org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223 b $ b)
在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293 )
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory。 preInstantiateSingletons(DefaultListableBeanFactory.java:615)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext。的java:479)
。在org.springframework.context.annotation.AnnotationConfigApplicationContext< INIT>(AnnotationConfigApplicationContext.java:73)
。在com.myproject.backend.common.ServiceContext.start(ServiceContext.java :293)
at com.myproject.run(AbstractServiceContainer.java:55)
at com.myproject..run(AbstractServiceContainer.java:1)
at io.dropwizard.cli.EnvironmentCommand .run(EnvironmentCommand.java:42)
at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:76)
at io.dropwizard.cli.Cli.run(Cli.java:70 )
at io.dropwizard.Application.run(Application.java:72)
at com.myproject..main(CombinedSe rviceContainer.java:106)
导致:org.springframework.data.mapping.PropertyReferenceException:找不到类型为MyEntity的属性用户!
at org.springframework.data.mapping.PropertyPath。< init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
位于org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
位于org.springframework。 data.repository.query.parser.Part。< init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree $ OrPart。< init>(PartTree.java :213)
at org.springframework.data.repository.query.parser.PartTree $ Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree $ Predicate。< init>(PartTree.java:301)
at org.springframework.data.repository。 query.parser.PartTree。< init>(PartTree.java:85)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery。< init>(PartTreeJpaQuery.java:60)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy $ CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:91)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy $ CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy的.java:168)
在org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy $ AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:69)
在org.springframework.data.repository.core.support .RepositoryFactorySupport $ QueryExecutorMethodInterceptor<初始化>(RepositoryFactorySupport.java:320)
。在org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
。在有机springframework.data.repository.core.support.Rep在org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
处org.springframework.data.jpa中的
。 repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
at org.springframework.beans。 factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
... 18 more



<问题: Spring Data JPA不支持查询主键的子集吗?或者是否需要为此实现自定义存储库方法?

解决方案

好的,我也试着用 @IdClass inst ead:

$ b $ p code $ @
$ @ b $ b $ J $ @ @ $ @ $ @ @ @ 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;



$ b @IdClass(Pk.class)
public class Pk implements Serializable {
private static final long serialVersionUID = - 3090221844117493661L;
私人整数类型;
private String userId;
$ b $ 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;
}

// 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());
返回结果;
}

// 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;
返回true;
}

}

这确实给了我一个不同的错误消息, NullPointerException ,这暗示我Spring Data JPA无法为 findAllByUserId(...)。相反,我做了一个自定义的查询方法实现:

  public interface MyEntityRepository扩展了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á,它的工作原理!


I have the following classes:

@Entity
@Table(name = "my_entity")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyEntity {
    @EmbeddedId
    private Pk id;

    public Pk getId() {
        return id;
    }

    public void setId(Pk id) {
        this.id = id;
    }

}

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

}

public interface MyEntityRepository extends JpaRepository<MyEntity, Pk> {

    List<MyEntity> findAllByUserId(String userId);

}

When I initialize Spring Data JPA I am getting the error:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myEntityRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property user found for type MyEntity!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:615)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
    at com.myproject.backend.common.ServiceContext.start(ServiceContext.java:293)
    at com.myproject.run(AbstractServiceContainer.java:55)
    at com.myproject..run(AbstractServiceContainer.java:1)
    at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:42)
    at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:76)
    at io.dropwizard.cli.Cli.run(Cli.java:70)
    at io.dropwizard.Application.run(Application.java:72)
    at com.myproject..main(CombinedServiceContainer.java:106)
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property user found for type MyEntity!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:85)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:60)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:91)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:168)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 18 more

Question: Does Spring Data JPA not support querying on a subset of a primary key? Or will I need to implement a custom repository method for this?

解决方案

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

}

...and voilá, it works!

这篇关于如何查询复合主键的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆