Unable to get list using conditions… here is a solution to the problem.
Unable to get list using conditions
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;
}
Image 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;
}
}
An image is an entity with the following properties: userId, name, size, preview.
userId + picture name is the composite primary key
I have fetched all rows with userId = 1
When I iterate through the list obtained. I get AAdhar (which is the first entry in the database) displayed 6 times instead of a different name each time.
I can’t figure out what the problem is.
Solution: Edit the correct image class code
Create the ImagePK class as described above
@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;
......}
Solution
I don’t think you’re creating the composite primary key the way you want. You can create a composite primary key in hibernate – like this
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
}
Use @IdClass
annotations in your Image
entity class
@Entity
@Table(name = "image")
@IdClass(ImagePK.class)
public class Image {
}