【问题标题】:Java Hibernate Collection Mapping : Not filtering specfic collection valueJava Hibernate 集合映射:不过滤特定集合值
【发布时间】:2016-08-01 09:59:46
【问题描述】:

问题说明:CountryState有收藏关系。获取一个国家,将其所有州与其关联。在许多情况下是需要的。现在在给定的情况下,我有国家id 和国家id,当使用国家ID 获取国家过滤时,是否有可能在Country 中获得单个State

Country.class

@Entity
@Repository
@Table(name="COUNTRY")
class Country implements Serializable{

@Id
@GeneratedValue(startegy=GenerationType.AUTO)
private long id;

@OneToMany(mappedBy="country", cascade={javax.persistence.CascadeType.ALL}, fetch=FetchType.EAGER)
private java.util.Set<State> states;
//Getters and setters


}

State.class

@Entity
@Repository
@Table(name="STATE")
class State implements Serializable{

@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", nullable=false, unique=true, updatable=true)
private long @Id

@ManyToOne
@JoinColumn(name="id")
private Country country;

//Getter and setter
}

我尝试过以下查询:

//This query works great when used in SQL editor. Getting one state     
select * from country left join state  ON country.id = state.id and state.id=3 
//Tried following
    setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

在 SQL 查询上使用并创建了条件,但我得到了所有状态。或者这个问题可以解决吗?我们有更好的选择吗?

【问题讨论】:

    标签: hibernate hibernate-mapping


    【解决方案1】:

    这不是 JPA 的工作方式。这会导致跟踪实体更改出现问题(JPA 提供者可能认为缺失的状态已从集合中删除)。

    然而,Hibernate 通过使用 @Filter@FilterDef 来支持这一点,请查看 this thread。以下是示例中使用的代码:

    @Entity
    public class A implements Serializable{
        @Id
        @Column(name = "REF")
        private int ref;
    
        @OneToMany
        @JoinColumn(name = "A_REF", referencedColumnName = "REF")   
        @Filter(name="test")
        private Set<B> bs;
    }
    
    @Entity
    @FilterDef(name="test", defaultCondition="other = 123")
    public class B implements Serializable{
        @Id
        @Column(name = "A_REF")
        private int aRef;
    
        @Id
        @Column(name = "OTHER")
        private int other;
    }
    
    Session session = entityManager.unwrap(Session.class);
    session.enableFilter("test");
    A a = entityManager.find(A.class, new Integer(0))
    a.getb().size() //Only contains b that are equals to 123
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多