1 /** 2 * Copyright 2011 meltmedia 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package org.xchain.namespaces.hibernate; 17 18 import org.apache.commons.jxpath.JXPathContext; 19 import org.hibernate.Session; 20 import org.xchain.annotations.Attribute; 21 import org.xchain.annotations.AttributeType; 22 import org.xchain.annotations.Element; 23 import org.xchain.framework.hibernate.HibernateLifecycle; 24 25 /** 26 * <p>The <code>save</code> command will execute a Hibernate save on the session with the specified entity. 27 * For more information about the <code>save</code> method, refer to the Hibernate documentation.</p> 28 * 29 * <p>This must reference an active <code>session</code>.</p> 30 * 31 * <code class="source"> 32 * <xchain:session xmlns:xchain="http://www.xchain.org/hibernate/1.0"> 33 * <xchain:transaction> 34 * ... 35 * <xchain:save entity="$myEntity"> 36 * ... 37 * </xchain:transaction> 38 * </xchain:session> 39 * </code> 40 * 41 * @author Devon Tackett 42 * @author Christian Trimble 43 * @author Josh Kennedy 44 * 45 * @see SessionCommand 46 * @see org.hibernate.Session#save(Object) 47 */ 48 @Element(localName="save") 49 public abstract class SaveCommand 50 extends AbstractSessionCommand 51 { 52 /** 53 * The entity to save. 54 */ 55 @Attribute(localName="entity", type=AttributeType.QNAME) 56 public abstract String getEntity( JXPathContext context); 57 public abstract boolean hasEntity(); 58 59 /** 60 * Save the entity at the given QName. Note that save will perform an insert 61 * immediately, no matter if this is inside or outside a transaction. 62 */ 63 public boolean execute( JXPathContext context ) 64 throws Exception 65 { 66 if (!hasEntity()) 67 throw new Exception("A save command must reference an entity."); 68 69 // Get the session from the context. 70 Session session = HibernateLifecycle.getCurrentSession(getName(context)); 71 72 // Get the entity. 73 Object entity = context.getValue(getEntity(context)); 74 75 if (entity == null) 76 throw new Exception("Unable to find entity at: " + getEntity(context)); 77 78 // Perform the save. 79 session.save(entity); 80 81 // The save is executed. 82 return false; 83 } 84 }