无法使用条件获取列表

Unable to fetch list using criteria

public static List<Image> getList(int userId) {
      Session session = HibernateUtil.openSession();
      Transaction tx = null;
      List<Image> results = null;
      try {
      tx = session.beginTransaction();

      Criteria crit = session.createCriteria(Image.class);
      crit.add(Restrictions.eq("userID",new Integer(userId)));
      results = crit.list();

      tx.commit();
      }
      catch (HibernateException e) {
          System.out.println("Problem in retrieving data from database");
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          } finally {
             session.close(); 
          }

    return results;

  }

图片class

@Entity
@Table(name = "image")
public class Image {
    @Id
    @Column(name = "userId")
    int userID;
    @Id
    @Column(name = "name")
    String name;
    @Column(name = "size")
    double size;
    @Column(name = "preview")
    byte[] preview;

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public String getName() {
        return name;
    }

    public Image() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Image(int userID, String name, double size, byte[] preview) {
        super();
        this.userID = userID;
        this.name = name;
        this.size = size;
        this.preview = preview;
    }

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

    public double getSize() {
        return size;
    }

    public void setSize(double size) {
        this.size = size;
    }

    public byte[] getPreview() {
        return preview;
    }

    public void setPreview(byte[] preview) {
        this.preview = preview;
    }

}

这是我的数据库

图像是一个具有以下属性的实体:用户 ID、名称、大小、预览。

userId + 图片名称为复合主键 我已经获取了所有 userId = 1 的行 当我遍历获得的列表时。我得到 AAdhar(这是数据库中的第一个条目)显示 6 次,而不是每次都显示不同的名称。 我无法找出问题所在。

解决方案:编辑正确的图像Class代码 如前所述创建 ImagePK class

 @Entity
    @Table(name = "image")
    @IdClass(ImagePK.class)
    public class Image {
        @Id
        @Column(name = "userId")
        int userID;
        @Id
        @Column(name = "name")
        String name;
        @Column(name = "size")
        double size;
        @Column(name = "preview")
        byte[] preview;
    ……}

我认为您创建复合主键的方式不正确。您可以在休眠中创建复合主键,如下所示 -

public class ImagePK implements Serializable {
    protected Integer userID;
    protected String name;

    public ImagePK() {}

    public ImagePK(Integer userID, String name) {
        this.userID = userID;
        this.name = name;
    }
    // equals, hashCode
}

在您的 Image 实体中使用 @IdClass 注释 class

@Entity
@Table(name = "image")
@IdClass(ImagePK.class)
public class Image {
}