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.tynamo.jpa.internal;
016    
017    import java.io.Serializable;
018    
019    import javax.persistence.EntityManager;
020    import javax.persistence.PersistenceException;
021    
022    import org.apache.tapestry5.internal.services.AbstractSessionPersistentFieldStrategy;
023    import org.apache.tapestry5.services.Request;
024    
025    /**
026     * Persists Hibernate entities by storing their id in the session.
027     * 
028     * @see PersistedEntity
029     */
030    public class EntityPersistentFieldStrategy extends AbstractSessionPersistentFieldStrategy
031    {
032            private final EntityManager entityManager;
033    
034            public EntityPersistentFieldStrategy(EntityManager entityManager, Request request)
035            {
036                    super("entity:", request);
037    
038                    this.entityManager = entityManager;
039            }
040    
041            @Override
042            protected Object convertApplicationValueToPersisted(Object newValue)
043            {
044                    try
045                    {
046                            Class entityName = newValue.getClass();
047                            Serializable id = (Serializable) entityManager.getEntityManagerFactory().getPersistenceUnitUtil()
048                                    .getIdentifier(newValue);
049                            return new PersistedEntity(entityName, id);
050                    }
051                    catch (PersistenceException ex)
052                    {
053                            throw new IllegalArgumentException(JPAMessages.entityNotAttached(newValue), ex);
054                    }
055            }
056    
057            @Override
058            protected Object convertPersistedToApplicationValue(Object persistedValue)
059            {
060                    PersistedEntity persisted = (PersistedEntity) persistedValue;
061    
062                    return persisted.restore(entityManager);
063            }
064    }