001 // Copyright 2008 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry5.internal.hibernate;
016
017 import org.apache.tapestry5.internal.services.AbstractSessionPersistentFieldStrategy;
018 import org.apache.tapestry5.services.Request;
019 import org.hibernate.HibernateException;
020 import org.hibernate.Session;
021
022 import java.io.Serializable;
023
024 /**
025 * Persists Hibernate entities by storing their id in the session.
026 *
027 * @see org.apache.tapestry5.internal.hibernate.PersistedEntity
028 */
029 public class EntityPersistentFieldStrategy extends AbstractSessionPersistentFieldStrategy
030 {
031 private final Session session;
032
033 public EntityPersistentFieldStrategy(Session session, Request request)
034 {
035 super("entity:", request);
036
037 this.session = session;
038 }
039
040 @Override
041 protected Object convertApplicationValueToPersisted(Object newValue)
042 {
043 try
044 {
045 String entityName = session.getEntityName(newValue);
046 Serializable id = session.getIdentifier(newValue);
047
048 return new PersistedEntity(entityName, id);
049 }
050 catch (HibernateException ex)
051 {
052 throw new IllegalArgumentException(HibernateMessages.entityNotAttached(newValue), ex);
053 }
054 }
055
056 @Override
057 protected Object convertPersistedToApplicationValue(Object persistedValue)
058 {
059 PersistedEntity persisted = (PersistedEntity) persistedValue;
060
061 return persisted.restore(session);
062 }
063 }