Hibernate条件查询不遵守多个限制

时间:2014-10-23 09:50:22

标签: java hibernate criteria

我正在尝试使用条件查询2个表。以下是方法:

   public UserEntity getUserOverView(long userId, String receiptMonth) {

  Session session = HibernateUtil.getSessionFactory().openSession();
   UserEntity user = new UserEntity();

  try {
     session.beginTransaction();

          Criteria criteria = session.createCriteria(UserEntity.class, "user")
           .createAlias("user.receiptEntitySet", "receipt")
           .add(Restrictions.eq("receipt.dateCreated", receiptMonth))
           .add(Restrictions.eq("user.userId", userId));


     user = (UserEntity) criteria.uniqueResult();

  } catch (Exception ex) {

     System.out.print(ex.getMessage());
  } finally {

     session.getTransaction().commit();
     session.close();

  }

  return user;

}

以上是成功尊重userId,但是,我想过滤收据上的'在另一张桌子上。它似乎忽略了收据月份'完全限制。

UserEntity:

    package za.co.skizzel.infrastructure.entities;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name="user")
public class UserEntity {

  @Id
  @GeneratedValue
  @Column(name="userId", unique = true, nullable = false, updatable = false )
  private Long userId;

  @Column(name="email")
  private String email;

  @Column(name="password")
  private String password;

  @Column(name="name")
  private String name;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "userEntity" , cascade = { CascadeType.ALL } )
  private Set<ReceiptEntity> receiptEntitySet;

   @OneToMany(fetch = FetchType.EAGER, mappedBy = "userEntity" , cascade = { CascadeType.ALL } )
   private Set<CategoryEntity> categoryEntitySet;

   public Set<CategoryEntity> getCategoryEntitySet() {
      return categoryEntitySet;
   }

   public void setCategoryEntitySet(Set<CategoryEntity> categoryEntitySet) {
      this.categoryEntitySet = categoryEntitySet;
   }

   public Long getUserId() {
      return userId;
   }

   public void setUserId(Long userId) {
      this.userId = userId;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public Set<ReceiptEntity> getReceiptEntitySet() {
      return receiptEntitySet;
   }

   public void setReceiptEntitySet(Set<ReceiptEntity> receiptEntitySet) {
      this.receiptEntitySet = receiptEntitySet;
   }

   public UserEntity(){};

   public UserEntity(long userId){
      this.userId = userId;
   };

}

ReceiptEntity:

    package za.co.skizzel.infrastructure.entities;


import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name="receipt")
public class ReceiptEntity {

  @Id
  @GeneratedValue
  @Column(name="ReceiptId", unique = true, nullable = false, updatable = false )
  private Long receiptId;

  @Column(name="alias")
  private String alias;

   @Column(name="categoryId")
   private long categoryId;

  @Column(name="DateCreated")
  private String dateCreated;

  @ManyToOne
  @JoinColumn(name="userId", nullable=false, insertable = false, updatable = false)
  private UserEntity userEntity;

   @OneToMany(fetch = FetchType.EAGER, mappedBy = "receiptEntity" , cascade = { CascadeType.ALL } )
   private Set<ImageEntity> imageEntitySet;

   private long userId;

   public long getUserId() {
      return userId;
   }

   public void setUserId(long userId) {
      this.userId = userId;
   }

   public long getCategoryId() {
      return categoryId;
   }

   public void setCategoryId(long categoryId) {
      this.categoryId = categoryId;
   }

   public Long getReceiptId() {
    return receiptId;
  }

  public void setReceiptId(Long receiptId) {
    this.receiptId = receiptId;
  }

  public String getAlias() {
    return alias;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  public String getDateCreated() {
    return dateCreated;
  }

  public void setDateCreated(String dateCreated) {
    this.dateCreated = dateCreated;
  }

  public UserEntity getUserEntity() {
    return userEntity;
  }

  public void setUserEntity(UserEntity userEntity) {
    this.userEntity = userEntity;
  }

   public ReceiptEntity() {};

}

不确定我做错了什么?任何指导都会受到赞赏吗?

由于 路加

修改

我期待的是:

select * from user, receipt where user.userId = '8' and receipt.dateCreated = 'January 2014'

2 个答案:

答案 0 :(得分:1)

这有用吗?

      Criteria criteria = session.createCriteria(UserEntity.class)
       .createAlias("receiptEntitySet", "receipt")
       .add(Restrictions.eq("receipt.dateCreated", receiptMonth))
       .add(Restrictions.eq("userId", userId));

修改

此查询将返回UserEntity作为整体,符合条件。例如,如果userEntity中只有一个ReceiptEntity receiptEntitySet dateCreated = receiptMonth,其中一个userEntity receiptEntitySet,那么两个userEntity都会List<ReceiptEntity> filteredReceipts = new ArrayList<ReceiptEntity>(); for (ReceiptEntity receipt : user.getReceiptEntitySet()) { if (receipt.getDateCreated().equals(receiptMonth) { filteredReceipts.add(receipt); } } Criteria criteria = session.createCriteria(ReceiptEntity.class) .createAlias("user", "user") .add(Restrictions.eq("dateCreated", receiptMonth)) .add(Restrictions.eq("user.userId", userId)); 中的收据实体。 {{1}}将附加实体(绑定到Hibernate会话)并将表示该对象的数据库状态,该对象包括两个收据实体。

您的选项取决于您的使用案例,但通常您可以将用户和收据保存在单独的字段中,您可以通过循环填写收据

{{1}}

或者,创建一个将获取它们的查询

{{1}}

希望这有帮助。

答案 1 :(得分:0)

你需要在这里做一些奇特的SQL。 SQL不知道如何将“2014年1月”与日期字段进行比较。此外,您不能只比较两个日期,因为月初的日期不等于月末(或日,或小时,或分钟......等)的日期,所以你需要从目标字段中提取月份和年份以进行过滤,并将每个月份与要过滤的月份和年份进行比较。

我认为,这些方面的某些内容可能会对您有所帮助:

    public void test(){
        SimpleDateFormat f = new SimpleDateFormat("MMM yyyy");
        Date d = null;
        String userId = "userId";
        try {
            d = f.parse("January 2014");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(d!= null){
            System.out.println("Date is: "+d.toString());
            Criteria c = this.getSession().createCriteria(UserEntity.class)
                .add(Restrictions.sqlRestriction("extract('month' from cast('"+d.toString()+"' as timestamp)) = extract('month' from reciept.dateCreated) and extract('year' from cast('"+d.toString()+"' as timestamp)) = extract('year' from reciept.dateCreated)"))
                .add(Restrictions.eq("userId", userId));
         }
    }

希望这有帮助。