具有hibernate中所有变量的对象的ID

时间:2013-07-31 17:36:43

标签: hibernate

使用这个类,我希望这个类的ID是它所有属性的值。这隐含意味着我只需要在数据库中存在这些值的行。如何在Hibernate中执行此操作?

public class WeatherState {
    private String weatherType;
    private double temperature;
}

1 个答案:

答案 0 :(得分:1)

当持久属性应该是WeatherState的直接属性时,@IdClass是可行的方法(从javax.persistence包导入持久性注释):

@Entity
@IdClass(WeatherStateId.class)
public class WeatherState {
    @Id private String weatherType;
    @Id private double temperature;
    //getters, setters
}

public class WeatherStateId implements Serializable {
    private String weatherType;
    private double temperature;
    //getters, setters, equals, hashcode
}

其他选项是使用@EmbeddedId

@Entity
public class WeatherState {
    @EmbeddedId private WeatherStateId weatherStateId;

    public WeatherStateId getWeatherStateId() {
        return weatherStateId;
    }

    public void setWeatherStateId(WeatherStateId weatherStateId) {
        this.weatherStateId = weatherStateId;
    }
}

@Embeddable
public class WeatherStateId implements Serializable {
    private String weatherType;
    private double temperature;
    //getters, setters, equals, hashcode
}

在两种情况下,提供equals和hashcode非常重要,如JPA 2.0规范中所述:

  

主键类必须定义equals和hashCode方法。该   这些方法的值相等的语义必须与之一致   密钥所在的数据库类型的数据库相等性   映射。