001// Copyright 2009, 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.internal.hibernate; 016 017import org.apache.tapestry5.internal.services.SessionApplicationStatePersistenceStrategy; 018import org.apache.tapestry5.services.ApplicationStateCreator; 019import org.apache.tapestry5.services.Request; 020import org.hibernate.Session; 021 022/** 023 * Persists Hibernate entities as SSOs by storing their primary key in the {@link org.apache.tapestry5.services.Session}. 024 * 025 * @see org.apache.tapestry5.internal.hibernate.PersistedEntity 026 */ 027public class EntityApplicationStatePersistenceStrategy extends SessionApplicationStatePersistenceStrategy 028{ 029 030 private final EntityPersistentFieldStrategy delegate; 031 032 public EntityApplicationStatePersistenceStrategy(Request request, Session hibernateSession) 033 { 034 super(request); 035 036 delegate = new EntityPersistentFieldStrategy(hibernateSession, null); 037 } 038 039 @SuppressWarnings("unchecked") 040 public <T> T get(Class<T> ssoClass, ApplicationStateCreator<T> creator) 041 { 042 final Object persistedValue = getOrCreate(ssoClass, creator); 043 044 if (persistedValue instanceof SessionRestorable) 045 { 046 Object restored = delegate.convertPersistedToApplicationValue(persistedValue); 047 048 // Maybe throw an exception instead? 049 if (restored == null) 050 { 051 set(ssoClass, null); 052 return (T) getOrCreate(ssoClass, creator); 053 } 054 055 return (T) restored; 056 } 057 058 return (T) persistedValue; 059 } 060 061 public <T> void set(Class<T> ssoClass, T sso) 062 { 063 final String key = buildKey(ssoClass); 064 065 if (sso == null) 066 { 067 getSession().setAttribute(key, null); 068 return; 069 } 070 071 Object persistable = delegate.convertApplicationValueToPersisted(sso); 072 073 getSession().setAttribute(key, persistable); 074 } 075 076}