我正在尝试使用Hibernate映射一些现有的表。
这很简单:我们的类别有多种语言的名称。
DDL如下:
create table language (
id integer not null auto_increment,
code varchar(2) not null,
unique (code),
primary key(id)
);
create table category (
id integer not null auto_increment,
parent_id integer default null,
ordr integer not null default 99,
primary key (id)
);
create table category_description (
category_id integer not null,
language_id integer not null,
title varchar(255) not null,
constraint foreign key (category_id) references category(id),
constraint foreign key (country_language_id) references country_language(id),
primary key (category_id, country_language_id)
);
现在我想要一个带有语言的地图,因为它的关键和描述(表category_description)就像它的值一样,如下所示:
private Map<Language, CategoryDescription> descriptions = new HashMap<Language, CategoryDescription>();
任何人都可以向我提供一些指示吗?我已经尝试了第311/312页中给出的'Java Persistence with Hibernate'中的示例,它类似于我的问题,但我只是没有得到它:(
答案 0 :(得分:2)
(您的DDL不一致,您创建表“语言”但引用表“country_language” - 我将假设后者)
以下是样本的Hibernate映射:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="false">
<class name="Language" table="country_language">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="code" type="string" length="2" unique="true" />
</class>
<class name="Category" table="category">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<map name="descriptions" table="category_description">
<key column="category_id" />
<map-key-many-to-many column="language_id" class="Language" />
<composite-element class="CategoryDescription">
<property name="title" type="string" length="255" />
</composite-element>
</map>
</class>
</hibernate-mapping>
但是,您根本不需要CategoryDescription
类(因为它只包含String
):
private Map<Language, String> descriptions;
和
<map name="descriptions" table="category_description">
<key column="category_id" />
<map-key-many-to-many column="language_id" class="Language" />
<element type="string" length="255" column="title" />
</map>
也可以。
请注意,在这两种情况下,Language
类都需要覆盖hashCode()
和equals()
才能成功查询生成的地图:
/* eclipse generated */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/* eclipse generated */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Language other = (Language) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}