Archive for August, 2007

252 APPENDIX A n MORE ADVANCED FEATURES (Personal web server) APPENDIX

Wednesday, August 22nd, 2007

252 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES By obtaining a JDBC connection from the session, it is of course possible to invoke stored procedures directly; however, you must be aware that the Hibernate session cache cannot track these updates. Events Hibernate 3 actually implements most of its functionality as event listeners. When you register a listener with Hibernate, the listener entirely supplants the default functionality. For example, the EJB 3 specific behavior required when using an EntityManager is achieved by plugging in a set of EJB 3 specific event listeners! If you look at the methods of the SessionImpl class, which is the internal Hibernate implementation of the Session interface, you ll see why this is the case. Most of the methods have a form very similar to that shown in Listing A-21. Listing A-21. The Implementation of a Typical Method in SessionImpl SaveOrUpdateEvent event = new SaveOrUpdateEvent(entityName, obj, this); listeners.getSaveOrUpdateEventListener().onSaveOrUpdate(event); The listeners field is an instance of SessionEventListenerConfig, which provides the requested event listener, or the default if none is specified. So, if your event listener is provided and doesn t call the default one, nothing else can. Event listeners are always registered globally for the event that they handle. You can register them in the configuration file or programmatically. Either way, you will need to map your implementation of one of the interfaces to the associated types, which you can look up in Table A-1. (The names are almost but not quite standardized.) Table A-1. The Listener Names and Their Corresponding Interfaces Type Name Listener auto-flush AutoFlushEventListener delete DeleteEventListener dirty-check DirtyCheckEventListener evict EvictEventListener flush FlushEventListener flush-entity FlushEntityEventListener load LoadEventListener load-collection InitializeCollectionEventListener lock LockEventListener merge MergeEventListener persist PersistEventListener post-delete PostDeleteEventListener post-insert PostInsertEventListener post-load PostLoadEventListener post-update PostUpdateEventListener
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

Web site development - APPENDIX A n MORE ADVANCED FEATURES 251 n

Wednesday, August 22nd, 2007

APPENDIX A n MORE ADVANCED FEATURES 251 n MORE ADVANCED FEATURES 251 Invoking Stored Procedures Data outlives application logic. This is a general rule of thumb, and as we can attest, it holds true in practice. The natural lifespan of a database will tend to see multiple applications. The lifespan of some of these applications will, in turn, tend to overlap, so that at any one time we expect substantially different code bases to be accessing the same data. To resolve such issues, databases usually provide their own programming language to allow complex business rules to be expressed and enforced within the boundary of the database itself. These languages are expressed in stored procedures essentially an API to the database. Often, free-form SQL access to such a database is denied, and only access through stored procedures is permitted. Barring errors in the code of the stored procedures themselves, this removes any risk of corruption. One final advantage of using stored procedures is that when a substantial calculation is required, the use of a stored procedure can reduce the network traffic involved. For example, if you invoke a stored procedure to calculate the grand total of a table of accounts, only the request and the result figure would need to traverse the network. The equivalent client-side implementation would need to acquire the value to be totaled from every row! Taking the client example from the Putting SQL into a Mapping section, we could replace the SQL logic in the tag with a call to a suitable stored procedure. The callable attribute is set to true to indicate that Hibernate needs to issue a call to a stored procedure instead of a standard query (see Listing A-19). Listing A-19. Mapping a Call to the Stored Procedure {call insertClient(?,?,?,?,?,?)} In the stored procedure definition (see Listing A-20), you will note that the order of the parameters to be passed in has been tailored to match the order in which they will be provided by Hibernate. Listing A-20. The Logic of the Stored Procedure CREATE PROCEDURE insertClient( p_name varchar(32), p_number varchar(10), p_streetname varchar(128), p_town varchar(32), p_city varchar(32), p_id int) AS BEGIN INSERT INTO client (id,name,number,streetname,town,city,country) VALUES (:p_id,:p_name,:p_number,:p_streetname,:p_town,:p_city,’UK’); END
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Web domain - 250 APPENDIX A n MORE ADVANCED FEATURES APPENDIX

Tuesday, August 21st, 2007

250 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES In addition to the three SQL terms for writing to the database, you can specify hand-rolled SQL for reading. This is appended as tags outside the class tag (see Listing A-18). They are not intrinsically a part of the mapping. However, you can specify that one of them should be used as the default loader for your class. Listing A-18. An Alternative Mapping File Defining a Default Loader …
SELECT id as {c.id}, ‘NOT SPECIFIED’ as {c.name}, number as {c.number}, streetname as {c.streetname}, town as {c.town}, city as {c.city} FROM Client WHERE id = ?
nTip Unfortunately, this technique is not quite as sophisticated as you might hope the custom SQL will not be invoked in general terms. Only if the id is explicitly supplied, as is the case when calling the Session class s get() method, will the default handling be overridden in favor of the loader query.
You want to have a cheap webhost for your apache application, then check apache web hosting services.

APPENDIX A n MORE ADVANCED FEATURES 249 n (Web design online)

Monday, August 20th, 2007

APPENDIX A n MORE ADVANCED FEATURES 249 n MORE ADVANCED FEATURES 249 the mapping file, you can dictate exactly how changes to an entity should be enforced. The disadvantage is that you will lose Hibernate s guarantee of cross-database platform portability. The advantage is that you can carry out operations that are not explicitly described in the mapping, such as calculating and inserting values in the process of carrying out an insert. The tags are , , and . All three work in the same way. If you take a look at the DDL script for this appendix, you will see that our client table includes seven fields, the last of which is the countryfield, as shown in Listing A-16. Listing A-16. The DDL Script to Create the Client Table create table client ( id int not null primary key, name varchar(32) not null, number varchar(10), streetname varchar(128), town varchar(32), city varchar(32), country varchar(32) ); We will, however, ignore the country field in our mapping file. We would like this to be automatically set to UK whenever a client entity is persisted. Depending on the database, this could be implemented as part of the view s support for writing operations, or as a trigger invoked when the other fields are written but we use the tag to specify the operation to perform. The necessary ordering of the parameters can be determined by running Hibernate with logging enabled for the org.hibernate.persister.entity level. You must do this before you add the mapping. Listing A-17 shows a suitably formatted element with the parameters suitably ordered. Note that the identifier field id is in the last position not the first, as you might have expected. Listing A-17. The Mapping File Using Explicit SQL to Update the Tables
insert into client(name,number,streetname,town,city,id,country) values (?,?,?,?,?,?,’UK’);

We recommend high quality webhost to host and run your jsp application: christian web host services.

248 APPENDIX (Unable to start debugging on the web server) A n MORE ADVANCED FEATURES APPENDIX

Sunday, August 19th, 2007

248 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES Listing A-15. The Revised Mapping
The behavior of the composite primary key is unchanged, but the SKU now becomes a simple property. The color entity is mapped as before. The caveat for this approach is the problem of writing data to the mapping. Some databases (for example, versions 4 and lower of MySQL) do not support writable views, and others may have only limited support for them. To avoid views in these circumstances, we must abandon complete portability in favor of database-specific SQL inserted directly into the mapping file. Putting SQL into a Mapping Hibernate provides three tags that can be used to override the default behavior when writing to the database. Instead of accepting the SQL generated by Hibernate from the information in
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

APPENDIX A n MORE ADVANCED FEATURES 247 n (Free web space)

Saturday, August 18th, 2007

APPENDIX A n MORE ADVANCED FEATURES 247 n MORE ADVANCED FEATURES 247 There are several dissatisfying aspects to the mapping in Listing A-13. First, rather than mapping our product table, we have mapped the link table. This makes sense when you consider that the primary key formed from the two columns of this table uniquely identifies a colored product, which the product table alone cannot do. Second, we are obliged to create a number of distinct objects to represent the class: the Product class itself, a class to represent the primary key (inevitable where a composite id occurs), a class to represent the other attributes of the product, and the Colorclass. Last, the use of the columns more than once within the mapping requires us to flag them so that they cannot be written this is a read-only mapping. Using a View Fortunately, most databases provide a simple mechanism for manipulating a schema so that it better matches the business requirements. A database view will allow you to put together a join that appears to be a table. By a suitable choice of columns from the existing tables, you can construct a view that is much easier to map (see Listing A-14). Listing A-14. A View on the Product Tables create view vwProduct (ProductKey,ColorKey,Id,SKU,ColorId) AS select p.id as ProductKey, c.id as ColorKey, p.id as Id, p.sku as SKU, c.id as ColorId from product p, product_color pc, color c where p.id = pc.product_id and pc.color_id = c.id; This view effectively reformats our table so that it has a correct (composite) primary key formed from the link table s two columns. It makes the SKU data available directly, and it retains the foreign key into the colortable. Listing A-15 is a much more natural mapping.
Check Tomcat Web Hosting services for best quality webspace to host your web application.

246 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Managed web hosting)

Friday, August 17th, 2007

246 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES Figure A-1. A problematic but legal schema Here, the product table represents a product (for example, a flashlight). The color table represents the colors in which it is sold. The link table named product_color then allows us to identify a product by stock keeping unit (SKU), and identify the colors in which it is available. If we do not mind the Product object retaining a set of colors (representing the colors in which it can be sold), then we have no problem; but if we want to distinguish between a red flashlight and a green one, things become more difficult (see Listing A-13). Listing A-13. A Fairly Direct Representation of the Product
We recommend high quality webhost to host and run your jsp application: christian web host services.

Web server info - APPENDIX A n MORE ADVANCED FEATURES 245 n

Thursday, August 16th, 2007

APPENDIX A n MORE ADVANCED FEATURES 245 n MORE ADVANCED FEATURES 245 Limitations of Hibernate First and foremost, Hibernate wants every entity to be identifiable with a primary key. Ideally, it would like this to be a surrogate key (a single column distinct from the fields of the table). Hibernate will accept a primary key that is not a surrogate key. For example, the username column might be used to uniquely identify an entry in the user table. Hibernate will also accept a composite key as its primary key, so that the username and hostname might be used to form the primary key if the username alone does not serve to identify the row. In the real world, things do not really work like that. Any database that has been around the block a few times is likely to have at least one table for which the primary key has been omitted. For instance, the contents of the table may not have needed to be involved in any relations with other tables. While this is still bad database design, the error is only exposed when Hibernate tries to map objects to data. It may be that adding a suitable surrogate key column is an option when this is the case, we urge you to do so. In practice, however, the fundamental schema may not be under the developer s control, or other applications may break if the schema is radically changed. In most scenarios, a developer will be able to arrange the creation of views or stored procedures. It may be possible to create the appearance of a suitable primary key using these if no other options present themselves, but you should consult with your database administrators, since a table for which no true primary key can be obtained is likely to cause long-term corruption of your data. Finally, if you can neither change a broken schema nor add views or stored procedures to ameliorate its effects, you have the option of obtaining a pure JDBC connection (see Listing A-12) from the session to the database, and carrying out traditional connected database access. This is the option of last resort, and is only truly of value when you anticipate being able to correct the faulty schema at some future time. Listing A-12. Obtaining a JDBC Connection from Hibernate SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); Connection connection = session.getConnection(); Hand-Rolled SQL While Hibernate cannot operate upon entities that lack primary keys, it is also extremely awkward to use Hibernate when there is a poor correspondence between the tables and the classes of your object model. Using a Direct Mapping Figure A-1 presents a fairly typical example of a valid database model that may be painful to represent in our mapping files.
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

244 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Web site templates)

Wednesday, August 15th, 2007

244 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES Listing A-11. Accessing a Hibernate Session in Map Mode package sample.map; import java.util.*; import org.hibernate.EntityMode; import org.hibernate.*; import org.hibernate.cfg.Configuration; public class AccessAsMap { private static final SessionFactory sessionFactory = new Configuration() .configure().buildSessionFactory(); public static void main(String[] args) throws Exception { System.out.println(”Preparing the Session objects”); Session session = sessionFactory.openSession(); Session mapSession = session.getSession(EntityMode.MAP); System.out.println(”Reading the map entries for XXX”); session.beginTransaction(); Map entity = (Map)mapSession.get(”sample.entity.Category”,new Long(2)); System.out.println(”Category Title: ” + entity.get(”title”)); System.out.println(”Contains Adverts:”); Set adverts = (Set)entity.get(”adverts”); Iterator adIt = adverts.iterator(); while(adIt.hasNext()) { Map advert = (Map)adIt.next(); System.out.println(advert.get(”title”)); } session.getTransaction().commit(); session.close(); System.out.println(”Done.”); } } This mode works much the same as the Dom4J mode changes written to the Map objects will be persisted exactly as if a normal persistent POJO object had been updated. Note that only the entities themselves will be represented as Maps not any of their attributes having a value type, or associations using Collection types. For example, in Listing A-11, the Category entity is represented as a Map, but its title attribute is represented as a String and its adverts attribute is represented as a Set however, the Setitself contains Advertentities represented as Maps.
If you are in need for chaep and reliable webhost to host your website, our recommendation is http web server services.

Frontpage web hosting - APPENDIX A n MORE ADVANCED FEATURES 243 n

Tuesday, August 14th, 2007

APPENDIX A n MORE ADVANCED FEATURES 243 n MORE ADVANCED FEATURES 243 Map names = new HashMap(); names.put(”user”,”sample.entity.User”); names.put(”advert”,”sample.entity.Advert”); names.put(”category”,”sample.entity.Category”); List entities = document.getRootElement().content(); Iterator eit = entities.iterator(); while(eit.hasNext()) { Node item = (Node)eit.next(); String entityName = (String)names.get(item.getName()); xmlSession.save(entityName,item); } session.getTransaction().commit(); session.close(); System.out.println(”Done.”); } } Unfortunately, the default value for the node attribute, if it is not explicitly applied to the class elements in the mapping files, is the short (unqualified) name of the class not the entity name, which defaults to the long (fully qualified) class name. Other Considerations When Using XML Entities The objects retrieved from Hibernate in the EntityMode.DOM4J session mode are Dom4J objects, but they are still Hibernate persistence entities. You can therefore manipulate these entities through the Dom4J API and persist these changes to the database without needing to access the entity as a POJO. Tools and APIs that process an XML document can therefore be applied to a Dom4J document extracted from Hibernate, and as long as it is still associated with the originating session, changes made to the document will be reflected in the database when the session is flushed or the transaction is committed. Hibernate and EJB 3 annotations do not provide support for the use of XML relational persistence. If you want to use this feature to import or export data for an annotated application, you will first need to generate appropriate XML-based mapping files from the annotated classes. Maps In addition to the default mode (POJO) and the XML mode (Dom4J) described previously, the Hibernate session can be accessed in one more way: as a map of name/value pairs. This mode is accessed by calling the getSession() method with a parameter of EntityMode.MAP (see Listing A-11).
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.