    001// Copyright 2008-2014 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.hibernate.web.internal;
    016
    017import org.apache.tapestry5.http.annotations.ImmutableSessionPersistedObject;
    018import org.apache.tapestry5.ioc.internal.util.InternalUtils;
    019import org.hibernate.Session;
    020
    021import java.io.Serializable;
    022
    023/**
    024 * Encapsulates a Hibernate entity name with an entity id.
    025 */
    026@ImmutableSessionPersistedObject
    027public class PersistedEntity implements SessionRestorable
    028{
    029    private static final long serialVersionUID = 897120520279686518L;
    030
    031    private final String entityName;
    032
    033    private final Serializable id;
    034
    035    public PersistedEntity(String entityName, Serializable id)
    036    {
    037        assert InternalUtils.isNonBlank(entityName);
    038        assert id != null;
    039
    040        this.entityName = entityName;
    041        this.id = id;
    042    }
    043
    044    @Override
    045    public Object restoreWithSession(Session session)
    046    {
    047        try
    048        {
    049            return session.get(entityName, id);
    050        } catch (Exception ex)
    051        {
    052            throw new RuntimeException(String.format("Failed to load session-persisted entity %s(%s): %s", entityName, id, ex),
    053                    ex);
    054        }
    055    }
    056
    057    @Override
    058    public String toString()
    059    {
    060        return String.format("<PersistedEntity: %s(%s)>", entityName, id);
    061    }
    062}