これは私が常に遭遇する問題です:
コレクションのコレクションを表す単一のテーブルを Hibernate で管理したいと思います。例:
- 地図の地図
- セット一覧
- リストのマップ
たとえば、次のように表現したいと思います。
クラスOwningClass{ 長いエンティティID; Map<文字列、List<要素>> mapOfLists; } クラス要素{ 文字列data_1; ブールデータ2; }
単一のテーブルとして:
OWNER (この要素の所有者への外部キー) MAP_KEY (varchar(30)) LIST_INDEX (整数) ELEMENT_DATA_1 (varchar(1020) ELEMENT_DATA_2 (ビット)
カスタムの休止状態コードがなければ不可能のようですが、それは構いません。しかし、そのカスタム コードがどのようなものであるべきかについて、誰かが何らかのガイダンスを持っていることを期待していました。
- AbstractPersistentCollection を拡張する必要がありますか?
- 複合ユーザータイプ?
複数のテーブルが問題なければ管理可能ですが、明らかに DB の観点からは不十分です。
ベストアンサー1
答えはhttps://xebia.com/blog/mapping-multimaps-with-hibernate/
これは 11 年前の長いブログ投稿です。キーコードは次のとおりです。
public class MultiMapType implements UserCollectionType {
public boolean contains(Object collection, Object entity) {
return ((MultiMap) collection).containsValue(entity);
}
public Iterator getElementsIterator(Object collection) {
return ((MultiMap) collection).values().iterator();
}
public Object indexOf(Object collection, Object entity) {
for (Iterator i = ((MultiMap) collection).entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Collection value = (Collection) entry.getValue();
if (value.contains(entity)) {
return entry.getKey();
}
}
return null;
}
public Object instantiate() {
return new MultiHashMap();
}
public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister) throws HibernateException {
return new PersistentMultiMap(session);
}
public PersistentCollection wrap(SessionImplementor session, Object collection) {
return new PersistentMultiMap(session, (MultiMap) collection);
}
public Object replaceElements(Object original, Object target, CollectionPersister persister, Object owner, Map copyCache, SessionImplementor session) throws HibernateException {
MultiMap result = (MultiMap) target;
result.clear();
Iterator iter = ( (java.util.Map) original ).entrySet().iterator();
while ( iter.hasNext() ) {
java.util.Map.Entry me = (java.util.Map.Entry) iter.next();
Object key = persister.getIndexType().replace( me.getKey(), null, session, owner, copyCache );
Collection collection = (Collection) me.getValue();
for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
Object value = persister.getElementType().replace( iterator.next(), null, session, owner, copyCache );
result.put(key, value);
}
}
return result;
}
}
ここでもいくつか話がありました:Hibernate のマルチマップ