无法使用条件获取列表

时间:2018-08-29 10:18:57

标签: java hibernate criteria composite-primary-key hibernate-annotations

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;

  }

图片类

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

}

这是我的数据库 enter image description here

图像是一个具有以下属性的实体:userId,name,size,preview。

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

解决方案:已编辑正确的图像类代码 创建提到的ImagePK类

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

1 个答案:

答案 0 :(得分:3)

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

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
}

@IdClass实体类中使用Image批注

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