用JPA Entity映射数据表查询出来f返回List
的时候发现表里满足条件得记录有三条,但实体查询出来结果三条记录都是拿第一条重复,分析发现是因为Entity实体没有指定主键字段或者指定的字段不唯一所导致的。比如:
@Entity
@Table(name = "my_table")
public class PoiPlaceEntity implements java.io.Serializable {
private String name;
private String time;
private String content;
private Double lat;
private Double lon;
@Id
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "time")
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Basic
@Column(name = "content")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Basic
@Column(name = "lat")
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
@Basic
@Column(name = "lon")
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
}
上面的实体中把name字段当作主键,但name不唯一,导致查询出来的结果中记录条数是对的,但仔细一看都是拿第一条记录重复的。其实只要从表里找一个唯一字段设置成主键就可以,比如上面的实体中经纬度坐标应该是唯一的,所以在lat
前面加个@Id
注解:
@Id
@Column(name = "lat")
public Double getLat() {
return lat;
}