使用Hibernate从db获取记录时出错

时间:2018-06-07 15:24:31

标签: java hibernate

我有一个Entity类,其主键类型为UUID。

这是我的实体类

@Entity
@Table(name = "LOG_IP", indexes = @Index(columnList = "IP"))
public class LOGIP {
    private UUID ID;
    private Long IP;
    private String COUNTRY;
    private String COUNTRYCODE;

    public LOGIP() {
    }

    public LOGIP(Long IP, String COUNTRY) {
        this.ID = UUID.nameUUIDFromBytes(String.valueOf(IP).getBytes());
        this.IP = IP;
        this.COUNTRY = COUNTRY;
    }

    @Id
    @Column(name = "ID", columnDefinition = "BINARY(16)", nullable = false)
    public UUID getID() {
        return ID;
    }

    public void setID(UUID ID) {
        this.ID = ID;
    }

    @Basic
    @Column(name = "IP")
    public Long getIP() {
        return IP;
    }

    public void setIP(Long IP) {
        this.IP = IP;
    }

    @Basic
    @Column(name = "COUNTRY")
    public String getCOUNTRY() {
        return COUNTRY;
    }

    public void setCOUNTRY(String COUNTRY) {
        this.COUNTRY = COUNTRY;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        LOGIP logip = (LOGIP) o;
        return Objects.equals(IP, logip.IP);
    }

    @Override
    public int hashCode() {
        return Objects.hash(IP);
    }
}

我正在尝试按特定ID查询数据。对于特定的UUID,我无法检索数据。

首先,我通过查询db中的所有数据进行测试,并在运行时检查特定的UUID。并且通过查询检索找到的条目。下面是代码。它打印与下面提到的这三个ID相关的记录。

String name = LOGIP.class.getName();
Query<LOGIP> query = session.createQuery("from " + name , LOGIP.class);
List<LOGIP> list = query.list();

for (LOGIP logip : list) {
    if (logip.getID().equals(UUID.fromString("4247D43F-4EF3-33C1-A9BC-3902E18DF1F7")) || logip.getID().equals(UUID.fromString("73B0AFE5-A54D-3130-868E-A5D2040A8A20")) ||logip.getID().equals(UUID.fromString("F94F32A3-A6B2-34C5-8B18-23C84964AB20"))) {
           System.out.println("logip = " + logip);
       }
}

如果我尝试通过设置参数进行查询,查询将返回空列表。

// This ID Returns record associated with it when queried by parameter
query.setParameter("id", UUID.fromString("4247D43F-4EF3-33C1-A9BC-3902E18DF1F7")); 

// Below ID's returns empty list when queried by parameter
query.setParameter("id", UUID.fromString("73B0AFE5-A54D-3130-868E-A5D2040A8A20")); 
query.setParameter("id", UUID.fromString("f94f32a3-a6b2-34c5-8b18-23c84964ab20"));

0 个答案:

没有答案