package org.hibernate.engine.spi;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.hibernate.EntityMode;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type;
public final class CollectionKey implements Serializable {
private final String role;
private final Serializable key;
private final Type keyType;
private final SessionFactoryImplementor factory;
private final int hashCode;
private EntityMode entityMode;
public CollectionKey(CollectionPersister persister, Serializable key) {
this(
persister.getRole(),
key,
persister.getKeyType(),
persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode(),
persister.getFactory()
);
}
public CollectionKey(CollectionPersister persister, Serializable key, EntityMode em) {
this( persister.getRole(), key, persister.getKeyType(), em, persister.getFactory() );
}
private CollectionKey(
String role,
Serializable key,
Type keyType,
EntityMode entityMode,
SessionFactoryImplementor factory) {
this.role = role;
this.key = key;
this.keyType = keyType;
this.entityMode = entityMode;
this.factory = factory;
this.hashCode = generateHashCode();
}
private int generateHashCode() {
int result = 17;
result = 37 * result + role.hashCode();
result = 37 * result + keyType.getHashCode( key, factory );
return result;
}
public String getRole() {
return role;
}
public Serializable getKey() {
return key;
}
@Override
public String toString() {
return "CollectionKey"
+ MessageHelper.collectionInfoString( factory.getCollectionPersister( role ), key, factory );
}
@Override
public boolean equals(Object other) {
if ( this == other ) {
return true;
}
if ( other == null || getClass() != other.getClass() ) {
return false;
}
final CollectionKey that = (CollectionKey) other;
return that.role.equals( role )
&& keyType.isEqual( that.key, key, factory );
}
@Override
public int hashCode() {
return hashCode;
}
public void serialize(ObjectOutputStream oos) throws IOException {
oos.writeObject( role );
oos.writeObject( key );
oos.writeObject( keyType );
oos.writeObject( entityMode.toString() );
}
public static CollectionKey deserialize(
ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException {
return new CollectionKey(
(String) ois.readObject(),
(Serializable) ois.readObject(),
(Type) ois.readObject(),
EntityMode.parse( (String) ois.readObject() ),
(session == null ? null : session.getFactory())
);
}
}