【发布时间】:2018-08-29 10:18:57
【问题描述】:
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;
}
}
图片是一个实体,具有以下属性: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;
……}
【问题讨论】:
-
我很惊讶
Image似乎没有主键。你能显示这个实体的代码吗? -
用户id和图片名是这张表的主键
-
我怀疑实体中没有很好地定义主键。键可能在表中(在 SQL 中)中定义得很好,但在实体中没有定义(带有 Java 注释)。那+一些休眠缓存可以解释这种行为。
-
@ArnaudDenoyelle 能否建议在我的主键是 UserId + 图像名称时如何在这种特殊情况下指定主键
-
我已经添加了 Image 类代码。请查看@ArnaudDenoyelle。谢谢
标签: java hibernate criteria composite-primary-key hibernate-annotations