从db获取数据时非常奇怪的行为

时间:2012-03-27 08:12:00

标签: hibernate jpa-2.0

Util test Case:

@Test
        public void validate() {
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("code", "23102");
            List<ZipCodes> list = (List<ZipCodes>)this.genericDAO.findByNamedQuery("zipCodesList.findByCode",params);
            if(list!=null){
                for(ZipCodes zipCodes: list)
                {
                    System.out.println(zipCodes.getCounty());
                    System.out.println(zipCodes.getStateCode());
                }
            }
        }

数据库选择查询及其数据:

从zip_codes中选择*,其中code ='23102'

CODE   STATE_CODE     COUNTY
23102   VA    GOOCHLAND 
23102   VA    HANOVER   
23102   VA    LOUISA

hql GENRATED IS:

select zipcodes0_.code as code11_, zipcodes0_.city as city11_, zipcodes0_.county as county11_, zipcodes0_.state_code as state4_11_ from zip_codes zipcodes0_ where zipcodes0_.code='23102'

Genrated数据的所有县名都相同。

不知道出了什么问题?

可以帮助我吗?

ZipCodes类

@Entity
@Table(name = "zip_codes")
@NamedQueries(value = {
        @NamedQuery(name = "zipCodesList.findByCode", query = "select a from ZipCodes a where a.code=:code")
        })
public class ZipCodes implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "code")
    private String code;

    @Column(name = "state_code")
    private String stateCode;

    @Column(name = "county")
    private String county;

    @Column(name = "city")
    private String city;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getStateCode() {
        return stateCode;
    }

    public void setStateCode(String stateCode) {
        this.stateCode = stateCode;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

我失踪的地方无法捕捉?

1 个答案:

答案 0 :(得分:0)

用作id的字段是个问题。这不是唯一的。和数据预先填充在db中。所以第一场比赛被退回了。

我使用复合键制作了密钥,结果是身份字段。因此问题得到解决。

public class ZipCodesPK implements Serializable {

    private String code;

    private String county;


    public ZipCodesPK() {
    }

    public ZipCodesPK(String code, String county) {
        super();
        this.code = code;
        this.county = county;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

}