001// Copyright 2011 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
015package org.apache.tapestry5.internal.jpa;
016
017import java.io.Serializable;
018
019import javax.persistence.EntityManager;
020
021import org.apache.tapestry5.http.annotations.ImmutableSessionPersistedObject;
022import org.apache.tapestry5.jpa.EntityManagerManager;
023
024/**
025 * Encapsulates a JPA entity name with an entity id.
026 */
027@ImmutableSessionPersistedObject
028public class PersistedEntity implements Serializable
029{
030    private static final long serialVersionUID = 897120520279686518L;
031
032    private final Class entityClass;
033
034    private final Object id;
035
036    private final String persistenceUnitName;
037
038    public PersistedEntity(final Class entityClass, final Object id,
039            final String persistenceUnitName)
040    {
041        this.entityClass = entityClass;
042        this.id = id;
043        this.persistenceUnitName = persistenceUnitName;
044    }
045
046    public Object restore(final EntityManagerManager entityManagerManager)
047    {
048        try
049        {
050            final EntityManager entityManager = entityManagerManager
051                    .getEntityManager(persistenceUnitName);
052
053            return entityManager.find(entityClass, id);
054        }
055        catch (final Exception ex)
056        {
057            throw new RuntimeException(String.format(
058                    "Failed to load session-persisted entity %s(%s): %s", entityClass.getName(),
059                    id, ex));
060        }
061    }
062
063    @Override
064    public String toString()
065    {
066        return String.format("<PersistedEntity: %s(%s)>", entityClass.getName(), id);
067    }
068}