Java Hibernate条件查询不考虑多个限制

Java Hibernate条件查询不考虑多个限制,java,hibernate,criteria,Java,Hibernate,Criteria,我正在尝试使用条件查询2个表。方法如下: public UserEntity getUserOverView(long userId, String receiptMonth) { Session session = HibernateUtil.getSessionFactory().openSession(); UserEntity user = new UserEntity(); try { session.beginTransaction();

我正在尝试使用条件查询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;
}

上面提到的是用户ID,但是,我想在另一个表中的“receiptMonth”上进行筛选。它似乎完全忽略了“receiptMonth”限制

用户实体:

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

}
这行吗

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

此查询将返回与条件匹配的整体
UserEntity
。例如,如果您在
receiptEntitySet
中有一个
userEntity
和两个
ReceiptEntity
s,其中一个具有
dateCreated=receiptMonth
,那么您将在
receiptEntitySet
中获得两个接收实体的
userEntity
。该
userEntity
将是附加的实体(绑定到Hibernate会话),并将表示该对象的数据库状态,其中包括两个接收实体

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

List<ReceiptEntity> filteredReceipts = new ArrayList<ReceiptEntity>();
for (ReceiptEntity receipt : user.getReceiptEntitySet()) {
    if (receipt.getDateCreated().equals(receiptMonth) {
        filteredReceipts.add(receipt);
    }
}

希望这有帮助。

您需要在这里执行一些高级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));
         }
    }

希望这能有所帮助。

您希望结果如何?如果您希望将其
receiptEntitySet
过滤为只包含给定
receiptMonth
UserEntity
,那么您的期望是错误的。如果此查询至少包含一个
ReceiptEntity
和给定的
dateCreated
,则应返回具有给定id的
UserEntity
及其所有字段。我希望我的查询仅返回基于给定userId和receiptMonth的结果。查看我的编辑。根据您的条件,您的查询将返回整个
UserEntity
。如果您有
userEntity
userId=1
以及
receiptEntitySet
中的两个
ReceiptEntity
,其中一个具有
creationDate=receiptMonth
,则您将获得两个接收实体的整个
userEntity
。如果您只需要一个与
receiptMonth
匹配的收据实体,您将需要另一个/不同的查询。您能提供一个例子吗?我已经编辑了我的答案,并添加了注释中提到的内容。我没有做日期比较,只是尝试查询使用该参数创建的所有记录(2014年1月)。
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));
    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));
         }
    }