Duplicates in Hibernate Query
I have a database that contains currently 2 different items but when i try to query the database the DAO returns a List of size 2 which is correct but each item in the list is the first item in the database inst开发者_开发问答ead of the two unique items . This has really puzzled me and I cant quite understand how or why it is doing this has anyone experienced this before?
public List<Workout> getHistory(String username) {
String sql = "from Workout w where w.username = '"+username+"'";
return template.find(sql);
}
@Entity
@Table(name="workout")
public class Workout {
private static Logger logger = Logger.getLogger(Workout.class);
@Id
@Column(name="username")
private String username;
@Column(name="added_date")
private String added_date;
@Lob
@Column(name="workout")
byte[] workout;
public byte[] getWorkout() {
return workout;
}
public void setWorkout(byte[] workout) {
this.workout = workout;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
}
Any help at all on this would be greatly appreciated.
Turns out there was no such problems with the unique ID, the problem was a serialization issue caused by the set up of the default serialization of my workout class. Fixed now for the mean time thanks for your help! Thanks in Advance Chris
Do you have two Workouts in the db with the same username?
If so, then you shouldn't be using username as the id.
I don't know your domain. But at a guess I'd give each workout a unique id (probably a Long) and then username could be foreign key to a User object.
So you then should have something like this:
@Entity
@Table(name="workout")
public class Workout {
private static Logger logger = Logger.getLogger(Workout.class);
@Id
@Column(name="id")
private Long id;
@Column(name="username")
private String username;
Hope this helps.
There might be a problem with unique key.
Make sure your @Id
fields represent the unique key.
精彩评论