Archive for August, 2007

Web design seattle - 242 APPENDIX A n MORE ADVANCED FEATURES APPENDIX

Monday, August 13th, 2007

242 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES 1 3 … Importing XML Entities The session in Dom4J entity mode can be used to import data into Hibernate as well as export it. The process is really just the export process in reverse although there is one gotcha to be aware of: by default, the entity names will be assumed to be the same as the element nodes that you attempt to persist from the Dom4J document. Unless your node attributes in the mapping files correspond exactly with the entity names used in the mapping files, calls to the session will need to include the explicit entity name being saved. Listing A-10 shows an example of a workaround for this issue, in which a hard-coded map translates short element names into full entity names, and the version of the save() method that takes an entity name string is invoked. When the class elements node attributes correspond exactly with entity names, this sort of approach becomes unnecessary. Listing A-10. Importing Entities from an XML Document package sample.xml; import java.util.*; import org.dom4j.*; import org.dom4j.io.SAXReader; import org.hibernate.*; import org.hibernate.cfg.Configuration; public class ImportXML { private static final SessionFactory sessionFactory = new Configuration() .configure().buildSessionFactory(); public static void main(String[] args) throws Exception { System.out.println(”Preparing the DOM Document”); SAXReader reader = new SAXReader(); Document document = reader.read(”catalog.xml”); System.out.println(”Preparing the Session objects”); Session session = sessionFactory.openSession(); Session xmlSession = session.getSession(EntityMode.DOM4J); System.out.println(”Importing the catalog from the document”); session.beginTransaction();
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

APPENDIX A n MORE ADVANCED FEATURES 241 n (Web host server)

Sunday, August 12th, 2007

APPENDIX A n MORE ADVANCED FEATURES 241 n MORE ADVANCED FEATURES 241 System.out.println(”Preparing the Session objects”); Session session = sessionFactory.openSession(); Session xmlSession = session.getSession(EntityMode.DOM4J); System.out.println(”Reading the catalog from the database”); session.beginTransaction(); export(xmlSession,root,”from User”); export(xmlSession,root,”from Advert”); export(xmlSession,root,”from Category”); session.getTransaction().commit(); session.close(); System.out.println(”Dumping the catalog to a file”); BufferedWriter writer = new BufferedWriter(new FileWriter(”catalog.xml”)); document.write(writer); writer.flush(); writer.close(); System.out.println(”Done.”); } public static void export(Session xmlSession,Element root,String hql) { Query query = xmlSession.createQuery(hql); List categories = query.list(); Iterator cit = categories.iterator(); while(cit.hasNext()) { Element element = (Element)cit.next(); root.add(element); } } } The code in Listing A-8 generates the catalog.xml file shown in Listing A-9. Note how the node attributes in the mapping file correspond to the positions of the elements and attributes in the exported XML file. Note also how setting the embed-xml attribute to false substitutes the id value for the generated XML in the elements at the catalog/category/advert path. Listing A-9. The XML Exported by Hibernate 48k original box and packaging
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

240 APPENDIX A (Web server setup) n MORE ADVANCED FEATURES APPENDIX

Saturday, August 11th, 2007

240 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES
Exporting XML Entities With the entity mappings marked up for XML relational persistence, the generation of output from an existing set of persistent entities is fairly simple. By obtaining a session with the entity mode configured for Dom4J, the entity proxies retrieved from that session will be org.dom4j.Node instances that can be manipulated with the normal Dom4J API. To access a Session object in this mode, you first open a conventional session, and then invoke the getSession() method on it, passing EntityMode.DOM4J as the sole parameter thus: Session = sessionFactory.openSession(); Session xmlSession = session.getSession(EntityMode.DOM4J); Once an appropriate Dom4J document has been populated with the entities (extracted from Hibernate in the normal way), the session can be closed, and the Dom4J document can be treated as a self-contained entity, as shown in Listing A-8. Listing A-8. Exporting the Advert Entities Using Dom4J package sample.xml; import java.io.*; import java.util.*; import org.dom4j.*; import org.hibernate.*; import org.hibernate.cfg.Configuration; public class ExportXML { private static final SessionFactory sessionFactory = new Configuration() .configure().buildSessionFactory(); public static void main(String[] args) throws Exception { System.out.println(”Preparing the DOM Document”); Document document = DocumentHelper.createDocument(); Element root = document.addElement(”catalog”);
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Web hosting company - APPENDIX A n MORE ADVANCED FEATURES 239 n

Friday, August 10th, 2007

APPENDIX A n MORE ADVANCED FEATURES 239 n MORE ADVANCED FEATURES 239


Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Web hosting comparison - 238 APPENDIX A n MORE ADVANCED FEATURES APPENDIX

Thursday, August 9th, 2007

238 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES be checked for changes. If the fields being checked have changed prior to the commit, then the commit will fail. Versioning is generally a simpler and more reliable approach, so we suggest that you use this whenever you need optimistic locking features. XML Relational Persistence Hibernate provides a feature that allows XML data to be mapped into the entity model for access using the normal session methods. This functionality is provided primarily so that data can be imported into and exported from the underlying relational data store it is not intended as a replacement for relational databases! The feature can be used for various purposes archiving data, implementing SOAP interfaces, and so on but the most common use is for the purposes of processing (and providing) external data feeds such as product catalogs. We show here how the example application in Chapter 3 (an advertisements database) can be configured to read and write appropriate XML feeds for the mapped entities. Hibernate requires the use of Dom4J as the API for XML access because Hibernate s internals already rely upon Dom4J to read configuration and mapping files. Adding Node Information to Mappings Two attributes are used to add all the XML-specific information to your existing mapping files: node and embed-xml. The node attribute applies to most tags that correspond to tables or columns in the database. The value can be a single string, in which case it represents an element name in the XML markup; or it can be preceded by a commercial at symbol (@), in which case it represents the attribute of an element. Paths can be indicated using forward slashes. This is the standard XPath syntax for identifying elements in an XML document. If set to true, the embed-xmlattribute indicates that the property or entity referenced should be included inline as XML. If set to false, it indicates that a reference to the primary key should be substituted instead. This is necessary because the DOM generation does not perform reference handling automatically so loops in the entity model references would result in infinite loops in XML generation if this option could not be set to true. Note that if embed-xmlis set to false for an association, generating XML output that references another entity will not automatically include a representation of the entity elsewhere in the generated document. This is your responsibility. Listing A-7 shows how our example Advert class from Chapter 3 might be marked up with nodeand embed-xml attributes. Listing A-7. The AdvertExample Classes from Chapter 3 Marked Up for XML Persistence
We recommend high quality webhost to host and run your jsp application: christian web host services.

Web space - APPENDIX A n MORE ADVANCED FEATURES 237 n

Wednesday, August 8th, 2007

APPENDIX A n MORE ADVANCED FEATURES 237 n MORE ADVANCED FEATURES 237 environment, it is not unlikely that Client A will close a browser window on the open record, never committing or canceling the transaction, so that the record remains locked until the session times out. Clearly this is not a satisfactory solution. Usually, you will not want to permit the alternative scenario, in which no locking is used, and the last person to save a record wins! The solution, versioning, is essentially a type of optimistic locking (see Chapter 8) . When any changes to an entity are stored, a version column is updated to reflect the fact that the entity has changed. When a subsequent user tries to commit changes to the same entity, the original version number will be compared against the current value if they differ, the commit will be rejected. The Hibernate/EJB 3 annotation mappings and the Hibernate XML-based mappings both provide a simple syntax for indicating which field should be used for storing the managed version information. The annotation for this field is shown in Listing A-5. Listing A-5. Marking the Version Attribute Using Annotations @Version protected int getVersionNum() { return versionNum; } The default optimistic locking strategy for Hibernate is versioning, so if you provide a element in your XML configuration, this will be used as long as you have enabled dynamic updates (as shown in Listing A-6). Listing A-6. Marking the Version Attribute Using XML Mappings The version attribute is defined in a very similar way to the normal property attribute configuration. The version can be of type long, integer, short, timestamp, or calendar (note that using the element is an equivalent alternative to the use of the element syntax). The element s optimistic-lock attribute can be used to override the default versioning-based optimistic locking strategy. You can disable it entirely (despite the presence of a version field) using a value of none. You can explicitly state that versioning should be used with a value of version. You can elect to use dirty checking, with the dirty and all options. If you elect not to use versioning, dirty checking offers an alternative form of optimistic locking. Here, the values of the entities are themselves checked to see if they have changed since the entity was originally obtained. As with versioning-based optimistic locking, the check against the database is carried out when the changes are committed. If an optimistic lock type of dirty is selected, then only those fields that have changed since the persistent entity was obtained will be checked (the Session keeps track of the appropriate state information). If an optimistic lock type of all is selected, then all the fields comprising the entity will
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

236 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Email web hosting)

Tuesday, August 7th, 2007

236 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES manager.close(); factory.close(); } } While the configuration of an EJB 3 application server falls well outside the scope of this book (which is a shame, because the topic is interesting see Pro EJB: Java Persistence API, by Mike Keith and Merrick Schincariol (Apress, 2006), for a good introduction to the subject), the use of an EntityManager deployed into an EJB 3 application server is straightforward. Typically in such an environment, the container manages the EntityManager. Listing A-4 demonstrates how to obtain a reference to an EntityManager in such an environment only very simple changes would be necessary in Listing A-3 to support this. Note that in this environment, there is no need to interact with the EntityManagerFactory the container manages the appropriate interaction with the factory in a way that is transparent to the user code. Listing A-4. Obtaining an EntityManager from the Container by Injection public class Ejb3Example { @PersistenceContext(unitName=”sampleManager”,type=EXTENDED) EntityManager manager; // } As Listing A-4 demonstrates, the combination of container-managed EntityManagers, annotations, and resource injection makes the acquisition of an EntityManagerobject trivially simple (and remember, the EntityManageris essentially the same as a Hibernate Sessionobject). Hibernate provides a couple of additional features to facilitate the transition of Hibernate 3 code to EJB 3. Where your application uses a Configuration (or an AnnotationConfiguration) object to programmatically configure the Hibernate application, there is now an alternative Ejb3Configuration class that can be used in a similar manner to provide the configuration information for the EJB 3 objects without the need for a configuration.xml file. The element of the Hibernate Tools Ant task conversely allows the configuration of the tasks to be drawn from the classpath s META-INF/configuration.xml file, instead of from an explicitly identified Hibernate configuration or properties file. Managed Versioning and Optimistic Locking While we have saved versioning for this appendix s discussion of advanced features, it is actually quite straightforward to understand and apply. Consider the following scenario: Client A loads and edits a record. Client B loads and edits the same record. Client A commits its edited record data. Client B commits its differently edited record data. While the scenario is simple, the problems it presents are not. If Client A establishes a transaction, then Client B may not be able to load and edit the same record. Yet in a web
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

APPENDIX A n MORE ADVANCED FEATURES 235 (Crystaltech web hosting) n

Friday, August 3rd, 2007

APPENDIX A n MORE ADVANCED FEATURES 235 n MORE ADVANCED FEATURES 235 Listings A-1 and A-2) containing the appropriate configuration information. From the EntityManagerFactory class, you can request EntityManager instances that are used to access the entities. You have probably already spotted that the EJB 3 Persistenceclass corresponds roughly to Configuration, that EntityManagerFactory is a dead ringer for SessionFactory, and that EntityManager is the analog of Session. The example code in Listing A-3 pushes this point home. The EntityManager instance is used in a very similar way to the Sessionclass shown throughout this book (although some of the method names are slightly different persist() in this example corresponds to Session s save() method). Listing A-3. Using EJB 3 Persistence in J2SE Code package com.hibernatebook.advanced; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; public class Ejb3Example { @SuppressWarnings(”unchecked”) public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory(”sampleManager”); EntityManager manager = factory.createEntityManager(); manager.getTransaction().begin(); manager.persist(new Sample(”FAQ”)); manager.persist(new Sample(”RTFM”)); manager.persist(new Sample(”PDQ”)); manager.persist(new Sample(”ASAP”)); manager.getTransaction().commit(); Query query = manager.createQuery(”from Sample”); manager.getTransaction().begin(); List list = (List)query.getResultList(); manager.getTransaction().commit(); for(Sample sample : list) { System.out.println(sample.getContent()); }
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Apache web server - 234 APPENDIX A n MORE ADVANCED FEATURES APPENDIX

Friday, August 3rd, 2007

234 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES
com.hibernatebook.advanced.Sample
The configuration file can contain multiple named
elements, each corresponding to a different configuration of the ORM environment. In the example in Listing A-1, we have created a single annotation-mapped entity. The
element then configures the implementation-specific (i.e., Hibernate-specific) properties. In Listing A-1, we have configured a database connection and dialect. When configuring a J2EE environment, the connection would usually be provided through generic elements of the persistence unit; Listing A-2 shows a configuration that takes advantage of this approach. Listing A-2. An EJB 3 persistence.xml Configuration File Using a JTA Data Source
java:comp/env/jdbc/advanced com.hibernatebook.advanced.Sample
Listing A-2 shows that the configuration file requires very little Hibernate-specific information. In a J2EE environment, it is possible at deployment time to substitute alternative EJB 3 providers for the providers indicated in the application s metadata. In a J2SE environment, the configuration information is accessed by creating an EntityManagerFactory class by calling the createEntityManagerFactory()method of the Persistence class, with the configured name of the persistence unit (shown in bold in
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

More Advanced Features APPENDIX A n n n (Web design templates)

Friday, August 3rd, 2007

More Advanced Features APPENDIX A n n n More Advanced Features APPENDIX A n n n In this appendix, we discuss some of the features that, strictly speaking, lie outside the scope of this book, but that you should be aware of if you go on to use Hibernate in more depth. EJB 3 and the EntityManager The third version of the Enterprise Java Beans specification, generally known as EJB 3, has recently been finalized. Among other features, EJB 3 includes a standard ORM technology that was significantly influenced by the design of Hibernate. You encountered this close relationship in Chapter 6 when we discussed Hibernate s use of the EJB 3 annotations for creating entity mappings. Annotations can be used throughout your EJB 3 applications to denote various settings. They are also used to mark for injection of resources from the container in a manner very like that of Spring s dependency injection (see Appendix C). HQL, which was discussed in Chapter 9, is very similar to the EJB QL used in EJB 3 environments generally speaking, your HQL queries can be used as EJB QL queries without change. Given these similarities, a Hibernate application can be converted into a portable EJB 3 application with surprisingly few changes. EJB 3 now supports both J2SE environments and those hosted within J2EE application servers; so even a stand-alone application can be written to take advantage of the EJB 3 features. The standard way to access the ORM components of an EJB 3 application is through the EntityManager. The Hibernate team provides appropriate libraries for download on their EntityManager site at http://entitymanager.hibernate.org. The EntityManager is configured through a standard file called persistence.xml, which must be provided in a META-INF directory accessible from the classpath (or, in a J2EE environment, from the root of the deployed archive). This file serves the same purpose as a conventional Hibernate configuration file (hibernate.cfg.xml), although its syntax is somewhat different. An example file is given in Listing A-1. Listing A-1. An EJB 3 persistence.xml Configuration File
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.