Archive for December, 2007

Bulk and batch operations The second HQL (JPA (Web design course)

Thursday, December 20th, 2007

Bulk and batch operations The second HQL (JPA QL) bulk operation we introduce is the DELETE: Query q = session.createQuery( “delete CreditCard c where c.stolenOn is not null” ); int updatedCreditCards = q.executeUpdate(); The same rules as for UPDATE statements apply: no joins, single entity class only, optional aliases, subqueries allowed in the WHERE clause. Just like SQL bulk operations, HQL (and JPA QL) bulk operations don t affect the persistence context, they bypass any cache. Credit cards or items in memory aren t updated if you execute one of these examples. The last HQL bulk operation can create objects directly in the database. Creating new objects directly in the database Let s assume that all your customers Visa cards have been stolen. You write two bulk operations to mark the day they were stolen (well, the day you discovered the theft) and to remove the compromised credit-card data from your records. Because you work for a responsible company, you have to report the stolen credit cards to the authorities and affected customers. So, before you delete the records, you extract everything that was stolen and create a few hundred (or thousand) StolenCreditCard objects. This is a new class you write just for that purpose: public class StolenCreditCard { private Long id; private String type; private String number; private String expMonth; private String expYear; private String ownerFirstname; private String ownerLastname; private String ownerLogin; private String ownerEmailAddress; private Address ownerHomeAddress; … // Constructors, getter and setter methods } You now map this class to its own STOLEN_CREDIT_CARD table, either with an XML file or JPA annotations (you shouldn t have any problem doing this on your own). Next, you need a statement that executes directly in the database, retrieves all compromised credit cards, and creates new StolenCreditCard objects: Query q = session.createQuery( “insert into StolenCreditCard (type, number, expMonth, expYear,
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

CHAPTER 12 Modifying objects efficiently the state of (Web hosting domain)

Thursday, December 20th, 2007

CHAPTER 12 Modifying objects efficiently the state of a persistent object from the database, if you know it s been modified behind the back of the persistence context. Hibernate and JPA offer DML operations that are a little more powerful than plain SQL. Let s look at the first operation in HQL and JPA QL, an UPDATE: Query q = session.createQuery(”update Item i set i.isActive = :isActive”); q.setBoolean(”isActive”, true); int updatedItems = q.executeUpdate(); This HQL statement (or JPA QL statement, if executed with the EntityManager) looks like an SQL statement. However, it uses an entity name (class name) and a property name. It s also integrated into Hibernate s parameter binding API. The number of updated entity objects is returned not the number of updated rows. Another benefit is that the HQL (JPA QL) UPDATE statement works for inheritance hierarchies: Query q = session.createQuery( “update CreditCard set stolenOn <= :now where type = 'Visa'" ); q.setTimestamp("now", new Date() ); int updatedCreditCards = q.executeUpdate(); The persistence engine knows how to execute this update, even if several SQL statements have to be generated; it updates several base tables (because Credit- Card is mapped to several superclass and subclass tables). This example also doesn t contain an alias for the entity class it s optional. However, if you use an alias, all properties must be prefixed with an alias. Also note that HQL (and JPA QL) UPDATE statements can reference only a single entity class; you can t write a single statement to update Item and CreditCard objects simultaneously, for example. Subqueries are allowed in the WHERE clause; any joins are allowed only in these subqueries. Direct DML operations, by default, don t affect any version or timestamp values of the affected entities (this is standardized in Java Persistence). With HQL, however, you can increment the version number of directly modified entity instances: Query q = session.createQuery( "update versioned Item i set i.isActive = :isActive" ); q.setBoolean("isActive", true); int updatedItems = q.executeUpdate(); (The versioned keyword is not allowed if your version or timestamp property relies on a custom org.hibernate.usertype.UserVersionType.)
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

Bulk and batch operations On the other hand, (Web hosting script)

Wednesday, December 19th, 2007

Bulk and batch operations On the other hand, operations that require massive amounts of data are best not executed in the application tier. You should move the operation closer to the location of the data, rather than the other way round. In an SQL system, the DML statements UPDATE and DELETE execute directly in the database and are often sufficient if you have to implement an operation that involves thousands of rows. More complex operations may require more complex procedures to run inside the database; hence, you should consider stored procedures as one possible strategy. You can fall back to JDBC and SQL at all times in Hibernate or Java Persistence applications. In this section, we ll show you how to avoid this and how to execute bulk and batch operations with Hibernate and JPA. 12.2.1 Bulk statements with HQL and JPA QL The Hibernate Query Language (HQL) is similar to SQL. The main difference between the two is that HQL uses class names instead of table names, and property names instead of column names. It also understands inheritance that is, whether you re querying with a superclass or an interface. The JPA query language, as defined by JPA and EJB 3.0, is a subset of HQL. Hence, all queries and statements that are valid JPA QL are also valid HQL. The statements we ll show you now, for bulk operations that execute directly in the database, are available in JPA QL and HQL. (Hibernate adopted the standardized bulk operations from JPA.) The available statements support updating and deleting objects directly in the database without the need to retrieve the objects into memory. A statement that can select data and insert it as new entity objects is also provided. Updating objects directly in the database In the previous chapters, we ve repeated that you should think about state management of objects, not how SQL statements are managed. This strategy assumes that the objects you re referring to are available in memory. If you execute an SQL statement that operates directly on the rows in the database, any change you make doesn t affect the in-memory objects (in whatever state they may be). In other words, any direct DML statement bypasses the Hibernate persistence context (and all caches). A pragmatic solution that avoids this issue is a simple convention: Execute any direct DML operations first in a fresh persistence context. Then, use the Hibernate Session or EntityManager to load and store objects. This convention guarantees that the persistence context is unaffected by any statements executed earlier. Alternatively, you can selectively use the refresh() operation to reload
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

CHAPTER 12 Modifying objects efficiently EntityManager em = (Mac os x web server)

Tuesday, December 18th, 2007

CHAPTER 12 Modifying objects efficiently EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); computer = em.merge(computer); tx.commit(); em.close(); A single call to merge() makes any modification and addition persistent. Remember that merge() isn t the same as reattachment: It returns a new value that you should bind to the current variable as a handle to current state after merging. Some cascading options aren t standardized, but Hibernate specific. You map these annotations (they re all in the org.hibernate.annotations package) if you re working with the Session API or if you want an extra setting for Entity- Manager (for example, org.hibernate.annotations.CascadeType.DELETE_ ORPHAN). Be careful, though custom cascading options in an otherwise pure JPA application introduce implicit object state changes that may be difficult to communicate to someone who doesn t expect them. In the previous sections, we ve explored the entity association cascading options with Hibernate XML mapping files and Java Persistence annotations. With transitive state changes, you save lines of code by letting Hibernate navigate and cascade modifications to associated objects. We recommend that you consider which associations in your domain model are candidates for transitive state changes and then implement this with cascading options. In practice, it s extremely helpful if you also write down the cascading option in the UML diagram of your domain model (with stereotypes) or any other similar documentation that is shared between developers. Doing so improves communication in your development team, because everybody knows which operations and associations imply cascading state changes. Transitive persistence isn t the only way you can manipulate many objects with a single operation. Many applications have to modify large object sets: For example, imagine that you have to set a flag on 50,000 Item objects. This is a bulk operation that is best executed directly in the database. 12.2 Bulk and batch operations You use object/relational mapping to move data into the application tier so that you can use an object-oriented programming language to process that data. This is a good strategy if you re implementing a multiuser online transaction processing application, with small to medium size data sets involved in each unit of work.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

Transitive persistence objects you wish to delete the code (Web site)

Monday, December 17th, 2007

Transitive persistence objects you wish to delete the code that removes an element from the collection is often in a different layer than the code that executes the delete() operation. With orphan deletion enabled, you can remove orphans from the collection, and Hibernate will assume that they re no longer referenced by any other entity. Note again that orphan deletion is implicit if you map a collection of components; the extra option is relevant only for a collection of entity references (almost always a ). Java Persistence and EJB 3.0 also support transitive state changes across entity associations. The standardized cascading options are similar to Hibernate s, so you can learn them easily. 12.1.4 Transitive associations with JPA The Java Persistence specification supports annotations for entity associations that enable cascading object manipulation. Just as in native Hibernate, each Entity- Manager operation has an equivalent cascading style. For example, consider the Category tree (parent and children associations) mapped with annotations: @Entity public class Category { private String name; @ManyToOne public Category parentCategory; @OneToMany(mappedBy = “parentCategory”, cascade = { CascadeType.PERSIST, CascadeType.MERGE } ) public Set childCategories = new HashSet(); … } You enable standard cascading options for the persist() and merge() operations. You can now create and modify Category instances in persistent or detached state, just as you did earlier with native Hibernate: Category computer = … // Loaded in a previous persistence context Category laptops = new Category(”Laptops”); Category laptopUltraPortable = new Category(”Ultra-Portable”); Category laptopTabletPCs = new Category(”Tablet PCs”); laptops.addChildCategory(laptopUltraPortable); laptops.addChildCategory(laptopTabletPCs); computer.setName(”Desktops and Laptops”); computer.addChildCategory(laptops);
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Web server info - CHAPTER 12 Modifying objects efficiently In certain situations,

Sunday, December 16th, 2007

CHAPTER 12 Modifying objects efficiently In certain situations, you want to delete an entity instance by removing a reference from a collection. In other words, you can guarantee that once you remove the reference to this entity from the collection, no other reference will exist. Therefore, Hibernate can delete the entity safely after you ve removed that single last reference. Hibernate assumes that an orphaned entity with no references should be deleted. In the example domain model, you enable this special cascading style for the collection (it s only available for collections) of bids, in the mapping of Item: You can now delete Bid objects by removing them from this collection for example, in detached state: Item anItem = … // Loaded in previous Session anItem.getBids().remove(aBid); anItem.getBids().remove(anotherBid); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.saveOrUpdate(anItem); tx.commit(); session.close(); If you don t enable the delete-orphan option, you have to explicitly delete the Bid instances after removing the last reference to them from the collection: Item anItem = … // Loaded in previous Session anItem.getBids().remove(aBid); anItem.getBids().remove(anotherBid); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.delete(aBid); session.delete(anotherBid); session.saveOrUpdate(anItem); tx.commit(); session.close(); Automatic deletion of orphans saves you two lines of code two lines of code that are inconvenient. Without orphan deletion, you d have to remember all the Bid
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Free web hosting music - Transitive persistence synthetic identifiers, this solves the problem.

Saturday, December 15th, 2007

Transitive persistence synthetic identifiers, this solves the problem. New instances have a null identifier property value, so Hibernate treats them as transient. Detached instances have a nonnull identifier value, so Hibernate treats them accordingly. It s rarely necessary to customize the automatic detection routines built into Hibernate. The saveOrUpdate() method always knows what to do with the given object (or any reachable objects, if cascading of save-update is enabled for an association). However, if you use a natural composite key and there is no version or timestamp property on your entity, Hibernate has to hit the database with a SELECT to find out if a row with the same composite identifier already exists. In other words, we recommend that you almost always use saveOrUpdate() instead of the individual save() or update() methods, Hibernate is smart enough to do the right thing and it makes transitive all of this should be in persistent state, no matter if new or old much easier to handle. We ve now discussed the basic transitive persistence options in Hibernate, for saving new instances and reattaching detached instances with as few lines of code as possible. Most of the other cascading options are equally easy to understand: persist, lock, replicate, and evict do what you would expect they make a particular Session operation transitive. The merge cascading option has effectively the same consequences as save-update. It turns out that object deletion is a more difficult thing to grasp; the delete-orphan setting in particular causes confusion for new Hibernate users. This isn t because it s complex, but because many Java developers tend to forget that they re working with a network of pointers. Considering transitive deletion Imagine that you want to delete a Category object. You have to pass this object to the delete() method on a Session; it s now in removed state and will be gone from the database when the persistence context is flushed and committed. However, you ll get a foreign key constraint violation if any other Category holds a reference to the deleted row at that time (maybe because it was still referenced as the parent of others). It s your responsibility to delete all links to a Category before you delete the instance. This is the normal behavior of entities that support shared references. Any value-typed property (or component) value of an entity instance is deleted automatically when the owning entity instance is deleted. Value-typed collection elements (for example, the collection of Image objects for an Item) are deleted if you remove the references from the owning collection.
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

CHAPTER 12 Modifying objects efficiently Session session =

Friday, December 14th, 2007

CHAPTER 12 Modifying objects efficiently Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // Update three old Category instances and insert the new one session.saveOrUpdate(laptops); tx.commit(); session.close(); Because you specify cascade=”save-update” on the childCategories collection, Hibernate determines what is needed to persist the objects to the database. In this case, it queues three SQL UPDATE statements (for laptops, laptop- UltraPortable, laptopTablePCs) and one INSERT (for laptopBags). The save- OrUpdate() method tells Hibernate to propagate the state of an instance to the database by creating a new database row if the instance is a new transient instance or updating the existing row if the instance is a detached instance. More experienced Hibernate users use saveOrUpdate() exclusively; it s much easier to let Hibernate decide what is new and what is old, especially in a more complex network of objects with mixed state. The only (not really serious) disadvantage of exclusive saveOrUpdate() is that it sometimes can t guess whether an instance is old or new without firing a SELECT at the database for example, when a class is mapped with a natural composite key and no version or timestamp property. How does Hibernate detect which instances are old and which are new? A range of options is available. Hibernate assumes that an instance is an unsaved transient instance if: The identifier property is null. The version or timestamp property (if it exists) is null. A new instance of the same persistent class, created by Hibernate internally, has the same database identifier value as the given instance. You supply an unsaved-value in the mapping document for the class, and the value of the identifier property matches. The unsaved-value attribute is also available for version and timestamp mapping elements. Entity data with the same identifier value isn t in the second-level cache. You supply an implementation of org.hibernate.Interceptor and return Boolean.TRUE from Interceptor.isUnsaved() after checking the instance in your own code. In the CaveatEmptor domain model, you use the nullable type java.lang.Longas your identifier property type everywhere. Because you re using generated,
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Transitive persistence Saving several new instances with transitive (Cheapest web hosting)

Thursday, December 13th, 2007

Transitive persistence Saving several new instances with transitive persistence Why do we have cascading operations? You could save the laptop object, as shown in the previous example, without using any cascade mapping. Well, consider the following case: Category computer = … // Loaded in a previous Session Category laptops = new Category(”Laptops”); Category laptopUltraPortable = new Category(”Ultra-Portable”); Category laptopTabletPCs = new Category(”Tablet PCs”); laptops.addChildCategory(laptopUltraPortable); laptops.addChildCategory(laptopTabletPCs); computer.addChildCategory(laptops); (Notice that the convenience method addChildCategory() sets both ends of the association link in one call, as described earlier in the book.) It would be undesirable to have to save each of the three new categories individually in a new Session. Fortunately, because you mapped the childCategories association (the collection) with cascade=”save-update”, you don t need to. The same code shown earlier, which saved the single Laptops category, will save all three new categories in a new Session: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // Persist all three new Category instances session.save(laptops); tx.commit(); session.close(); You re probably wondering why the cascade style is called cascade=”save-update” rather then merely cascade=”save”. Having just made all three categories persistent previously, suppose you make the following changes to the category hierarchy in a subsequent event, outside of a Session (you re working on detached objects again): laptops.setName(”Laptop Computers”); // Modify laptopUltraPortable.setName(”Ultra-Portable Notebooks”); // Modify laptopTabletPCs.setName(”Tablet Computers”); // Modify Category laptopBags = new Category(”Laptop Bags”); laptops.addChildCategory(laptopBags); // Add You add a new category (laptopBags) as a child of the Laptops category, and modify all three existing categories. The following code propagates all these changes to the database:
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

CHAPTER 12 Modifying objects efficiently Creating a new (Most popular web site)

Wednesday, December 12th, 2007

CHAPTER 12 Modifying objects efficiently Creating a new category in a detached fashion Let s do the same thing again, but this time create the link between Computer and Laptops outside of the persistence context scope: Category computer = (Category) session.get() // Loaded in previous Session Category laptops = new Category(”Laptops”); computer.getChildCategories().add(laptops); laptops.setParentCategory(computer); You now have the detached fully initialized (no proxy) computer object, loaded in a previous Session, associated with the new transient laptops object (and vice versa). You make this change to the objects persistent by saving the new object in a second Hibernate Session, a new persistence context: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // Persist one new category and the link to its parent category session.save(laptops); tx.commit(); session.close(); Hibernate inspects the database identifier property of the laptops.parentCategory object and correctly creates the reference to the Computer category in the database. Hibernate inserts the identifier value of the parent into the foreign key field of the new Laptops row in CATEGORY. You can t obtain a detached proxy for computer in this example, because computer.getChildCategories() would trigger initialization of the proxy and you d see a LazyInitializationException: The Session is already closed. You can t walk the object graph across uninitialized boundaries in detached state. Because you have cascade=”none” defined for the parentCategory association, Hibernate ignores changes to any of the other categories in the hierarchy (Computer, Electronics)! It doesn t cascade the call to save() to entities referred by this association. If you enabled cascade=”save-update” on the mapping of parentCategory, Hibernate would navigate the whole graph of objects in memory, synchronizing all instances with the database. This is an obvious overhead you d prefer to avoid. In this case, you neither need nor want transitive persistence for the parent- Category association.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.