国际化数据库的Hibernate映射

时间:2017-01-24 16:19:26

标签: java internationalization hibernate-mapping hibernate-criteria

我希望根据hibernate查询中提供的语言环境从数据库中获取国际内容。这是关于hibernate映射的问题,但如果我的错误,请随意提出更好的数据库设计。

我的数据库设计(简化): db design 所以我有不可翻译数据的表格和附加翻译内容的表格,但附加字段" locale"区分语言。

我的 java类看起来像这样:

public class Car {

private Long id;
private Long length;
private Long weight;
private CarTranslated carTranslated;

// getters and setters

public class CarTranslated {

private Long id;
private Long carId;
private String desc;

// getters and setters

我希望能够通过单一查询获得一辆车。使用常规jdbc,我会使用类似 sql query

的内容
public Car getById(Long id, Locale locale) {
Car c = new Car();
String sql = "select c.car_id, c.length, c.weight, ct.id, ct.descryption, 
ct.car_id as "Translated car_id" from car c join car_translated ct on
(c.car_id =   ct.car_id) where c.car_id ="+ id+" and ct.locale ='"+locale+"'";

// code to set fields of the object using ResultSet

return c;
}

这个设置的hibernate注释映射和查询是什么?我尝试了几次但无济于事。目前我最好的尝试如下:

映射:

@Entity
@Table(name="CAR")
public class Car {

@Id
@Column(name="car_id")
private Long carId;

@Column (name="weight")
private Long carWeight;

@Column (name="length")
private Long carLength;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="CAR_ID")
private CarTranslated localized;

// getters and setters

@Entity
@Table(name="CAR_TRANSLATED")
public class CarTranslated {

@Id
@Column (name="id")
private Long id;

@Column (name="car_id")
private Long carId;

@Column (name="descryption")
private String desc;

@Column(name="locale")
private Locale locale;

DAO:

public Car getCarById(Locale locale, Long id) {
    Car car = new Car();
    try {
        Session session = HibernateUtils.getSessionFactory().openSession();
        Criteria cr = session.createCriteria(Car.class)
            .add(Restrictions.eq("carId", id));
        Criteria cr1 = session.createCriteria(CarTranslated.class)
            .add(Restrictions.eq("locale", locale));

        car = (Car) cr.uniqueResult();
        car.setLocalized((CarTranslated) cr1.uniqueResult());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return car;
}

这是一种解决方法,我想知道这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

映射到FK时,两列都应该有注释。 (JavaDoc