我正在尝试构建一个多语言数据库,因此我使用this database design作为我的方法。
现在我有两个问题/问题:
LocalizedEvent
并给出categoryId。如何使用Hibernate Criteria API在LocalizedCategory表上进行内连接?使用SQL,我会将此语句用于获取所有LocalizedEvent
+ LocalizedCategory
:
SELECT * FROM event e
INNER JOIN
localized_event le ON (le.event_id = e.event_id)
INNER JOIN
localized_category lc ON (lc.category_id = e.category_id)
WHERE
le.locale = 'de' AND lc.locale = 'de'
我目前的方法看起来没有LocalizedCategory
(使用Criteria API):
Criteria c = session.createCriteria(LocalizedEvent.class, "localizedEvent");
c.createAlias("localizedEvent.event", "event");
c.createAlias("event.category", "category");
c.add(Restrictions.eq("category.categoryId", categoryId));
c.add(Restrictions.eq("localizedEvent.locale", language));
LocalizedEvent
应该有一个属性localizedCategory
,但我不想保存此localizedCategory
的ID(因此我正在使用@Transient
注释) LocalizedEvent表,例如使用ManyToOne关系(加入LOC_CATEGORY_ID
)。但我认为不可能这样做,不是吗?我必须将这个瞬态字段映射到LocalizedEvent
“手动”,因为Hibernate不支持这种映射(如果我是对的)。
(使用JDBC这个属性/映射不会导致任何问题,因为我可以轻松地创建内部联接并将属性localizedCategory
分配给RowMapper中的LocalizedEvent
左右。)我的实体看起来像这样:
事件
@Entity
@Table(name = "EVENT")
public class Event {
@Id
@GeneratedValue
@Column(name = "EVENT_ID", unique = true)
private Long eventId;
@Column(name = "DATE")
private Date date;
@OneToMany(mappedBy = "event")
private Set<LocalizedEvent> localizedEvents;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID")
private Category category;
}
LocalizedEvent
@Entity
@Table(name = "LOCALIZED_EVENT")
public class LocalizedEvent {
@Id
@GeneratedValue
@Column(name = "LOC_EVENT_ID")
private Long locEventId;
@ManyToOne
@JoinColumn(name = "EVENT_ID")
private Event event;
@Transient
private LocalizedCategory localizedCategory;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "LOCALE")
private String locale;
}
分类
@Entity
@Table(name = "CATEGORY")
public class Category {
@Id
@GeneratedValue
@Column(name = "CATEGORY_ID", unique = true)
private Long categoryId;
@OneToMany(mappedBy = "category")
private Set<LocalizedCategory> localizedCategories;
@OneToMany(mappedBy = "category")
private Set<Event> events;
}
LocalizedCategory
@Entity
@Table(name = "LOCALIZED_CATEGORY")
public class LocalizedCategory {
@Id
@GeneratedValue
@Column(name = "LOC_CATEGORY_ID")
private Long locCategoryId;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID")
private Category category;
@Column(name = "NAME")
private String name;
@Column(name = "LOCALE")
private String locale;
}