gpt4 book ai didi

java - 无法使用条件获取列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:15 26 4
gpt4 key购买 nike

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

最佳答案

我认为您创建复合主键的方式不正确。您可以像下面这样在 hibernate 中创建复合主键 -

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注解

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

关于java - 无法使用条件获取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com