Archive for October, 2007

Free web hosts - CHAPTER 2 Starting a project The HibernateToolTask definition

Wednesday, October 31st, 2007

CHAPTER 2 Starting a project The HibernateToolTask definition for Ant is the same as before. We assume that you ll reuse most of the build file introduced in previous sections, and that references such as project.classpath are the same. The task is set with WORKDIR/src as the default destination directory for all generated artifacts. A is a Hibernate tool configuration that can connect to a database via JDBC and read the JDBC metadata from the database catalog. You usually configure it with two options: database connection settings (the properties file) and an optional reverse-engineering customization file. The metadata produced by the tool configuration is then fed to exporters. The example Ant target names two such exporters: the hbm2hbmxml exporter, as you can guess from its name, takes Hibernate metadata (hbm) from a configuration, and generates Hibernate XML mapping files; the second exporter can prepare a hibernate.cfg.xml file that lists all the generated XML mapping files. Before we talk about these and various other exporters, let s spend a minute on the reverse-engineering customization file and what you can do with it. 2.3.2 Customizing reverse engineering JDBC metadata that is, the information you can read from a database about itself via JDBC often isn t sufficient to create a perfect XML mapping file, let alone Java application code. The opposite may also be true: Your database may contain information that you want to ignore (such as particular tables or columns) or that you wish to transform with nondefault strategies. You can customize the reverse- engineering procedure with a reverse-engineering configuration file, which uses an XML syntax. Let s assume that you re reverse-engineering the Hello World database you created earlier in this chapter, with its single MESSAGES table and only a few columns. With a helloworld.reveng.xml file, as shown in listing 2.17, you can customize this reverse engineering. Listing 2.17 Configuration for customized reverse engineering B C
D

E
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

Reverse engineering a legacy database Hibernate mapping metadata (Kids web site)

Wednesday, October 31st, 2007

Reverse engineering a legacy database Hibernate mapping metadata has many more options, most of which are related to reverse engineering, as to how XML mapping files, Java code, or even whole application skeletons can be generated automatically from an existing database schema. We ll first show you how to write an Ant target that can load an existing database into a Hibernate metadata model. Next, you ll apply various exporters and produce XML files, Java code, and other useful artifacts from the database tables and columns. 2.3.1 Creating a database configuration Let s assume that you have a new WORKDIR with nothing but the lib directory (and its usual contents) and an empty src directory. To generate mappings and code from an existing database, you first need to create a configuration file that contains your database connection settings: hibernate.dialect = org.hibernate.dialect.HSQLDialect hibernate.connection.driver_class = org.hsqldb.jdbcDriver hibernate.connection.url = jdbc:hsqldb:hsql://localhost hibernate.connection.username = sa Store this file directly in WORKDIR, and name it helloworld.db.properties. The four lines shown here are the minimum that is required to connect to the database and read the metadata of all tables and columns. You could have created a Hibernate XML configuration file instead of hibernate.properties, but there is no reason to make this more complex than necessary. Write the Ant target next. In a build.xml file in your project, add the following code:
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

CHAPTER 2 Starting a project Session session = (Business web site)

Wednesday, October 31st, 2007

CHAPTER 2 Starting a project Session session = (Session) entityManager.getDelegate(); Or you can get a Session injected into an EJB component (although this only works in the JBoss Application Server): @Stateless public class MessageHandlerBean implements MessageHandler { @PersistenceContext Session session; … } In rare cases, you can fall back to plain JDBC interfaces from the Hibernate Session: Connection jdbcConnection = session.connection(); This last option comes with some caveats: You aren t allowed to close the JDBC Connection you get from Hibernate this happens automatically. The exception to this rule is that in an environment that relies on aggressive connection releases, which means in a JTA or CMT environment, you have to close the returned connection in application code. A better and safer way to access a JDBC connection directly is through resource injection in a Java EE 5.0. Annotate a field or setter method in an EJB, an EJB lis tener, a servlet, a servlet filter, or even a JavaServer Faces backing bean, like this: @Resource(mappedName=”java:/HelloWorldDS”) DataSource ds; So far, we ve assumed that you work on a new Hibernate or JPA project that involves no legacy application code or existing database schema. We now switch perspectives and consider a development process that is bottom-up. In such a scenario, you probably want to automatically reverse-engineer artifacts from an existing database schema. 2.3 Reverse engineering a legacy database Your first step when mapping a legacy database likely involves an automatic reverse-engineering procedure. After all, an entity schema already exists in your database system. To make this easier, Hibernate has a set of tools that can read a schema and produce various artifacts from this metadata, including XML mapping files and Java source code. All of this is template-based, so many customizations are possible. You can control the reverse-engineering process with tools and tasks in your Ant build. The HibernateToolTask you used earlier to export SQL DDL from
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Starting a Java Persistence project Object/relational mapping metadata, (Top web site)

Tuesday, October 30th, 2007

Starting a Java Persistence project Object/relational mapping metadata, but here we want to show how you can use a Hibernate API in your JPA application, when needed. Obviously, importing a Hibernate API into your code makes porting the code to a different JPA provider more difficult. Hence, it becomes critically important to isolate these parts of your code properly, or at least to document why and when you used a native Hibernate feature. You can fall back to Hibernate APIs from their equivalent JPA interfaces and get, for example, a Configuration, a SessionFactory, and even a Session whenever needed. For example, instead of creating an EntityManagerFactory with the Persistence static class, you can use a Hibernate Ejb3Configuration: Ejb3Configuration cfg = new Ejb3Configuration(); EntityManagerFactory emf = cfg.configure(”/custom/hibernate.cfg.xml”) .setProperty(”hibernate.show_sql”, “false”) .setInterceptor( new MyInterceptor() ) .addAnnotatedClass( hello.Message.class ) .addResource( “/Foo.hbm.xml”) .buildEntityManagerFactory(); AnnotationConfiguration hibCfg = cfg.getHibernateConfiguration(); The Ejb3Configuration is a new interface that duplicates the regular Hibernate Configuration instead of extending it (this is an implementation detail). This means you can get a plain AnnotationConfiguration object from an Ejb3Configuration, for example, and pass it to a SchemaExport instance programmatically. The SessionFactory interface is useful if you need programmatic control over the second-level cache regions. You can get a SessionFactory by casting the EntityManagerFactory first: HibernateEntityManagerFactory hibEMF = (HibernateEntityManagerFactory) emf; SessionFactory sf = hibEMF.getSessionFactory(); The same technique can be applied to get a Session from an EntityManager: HibernateEntityManager hibEM = (HibernateEntityManager) em; Session session = hibEM.getSession(); This isn t the only way to get a native API from the standardized EntityManager. The JPA specification supports a getDelegate() method that returns the underlying implementation:
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

CHAPTER 2 Starting a project This completes our

Tuesday, October 30th, 2007

CHAPTER 2 Starting a project This completes our first example with managed EJB components and integrated JPA. You can probably already see how automatic transaction demarcation and EntityManager injection can improve the readability of your code. Later, we ll show you how stateful session beans can help you implement sophisticated conversations between the user and the application, with transactional semantics. Furthermore, the EJB components don t contain any unnecessary glue code or infrastructure methods, and they re fully reusable, portable, and executable in any EJB 3.0 container. NOTE Packaging of persistence units We didn t talk much about the packaging of persistence units you didn t need to package the Hello World example for any of the deployments. However, if you want to use features such as hot redeployment on a full application server, you need to package your application correctly. This includes the usual combination of JARs, WARs, EJB-JARs, and EARs. Deployment and packaging is often also vendor-specific, so you should consult the documentation of your application server for more information. JPA persistence units can be scoped to JARs, WARs, and EJB-JARs, which means that one or several of these archives contains all the annotated classes and a META-INF/persistence. xml configuration file with all settings for this particular unit. You can wrap one or several JARs, WARs, and EJB-JARs in a single enterprise application archive, an EAR. Your application server should correctly detect all persistence units and create the necessary factories automatically. With a unit name attribute on the @PersistenceContext annotation, you instruct the container to inject an EntityManager from a particular unit. Full portability of an application isn t often a primary reason to use JPA or EJB 3.0. After all, you made a decision to use Hibernate as your JPA persistence provider. Let s look at how you can fall back and use a Hibernate native feature from time to time. 2.2.4 Switching to Hibernate interfaces You decided to use Hibernate as a JPA persistence provider for several reasons: First, Hibernate is a good JPA implementation that provides many options that don t affect your code. For example, you can enable the Hibernate second-level data cache in your JPA configuration, and transparently improve the performance and scalability of your application without touching any code. Second, you can use native Hibernate mappings or APIs when needed. We discuss the mixing of mappings (especially annotations) in chapter 3, section 3.3,
We recommend high quality webhost to host and run your jsp application: christian web host services.

Starting a Java Persistence project InitialContext initialContext = (Best web design)

Monday, October 29th, 2007

Starting a Java Persistence project InitialContext initialContext = new InitialContext(); // Look up the stateless MessageHandler EJB MessageHandler msgHandler = (MessageHandler) initialContext .lookup(”MessageHandlerBean/local”); // Call the stateless EJB msgHandler.saveMessages(); msgHandler.showMessages(); // Shut down EJB container EJB3StandaloneBootstrap.shutdown(); } } The first command in main() boots the server s kernel and deploys the base services found in the service configuration files. Next, the datasource factory configuration you created earlier in helloworld-beans.xml is deployed, and the datasource is bound to JNDI by the container. From that point on, the container is ready to deploy EJBs. The easiest (but often not the fastest) way to deploy all EJBs is to let the container search the whole classpath for any class that has an EJB annotation. To learn about the many other deployment options available, check the JBoss AS documentation bundled in the download. To look up an EJB, you need an InitialContext, which is your entry point for the JNDI registry. If you instantiate an InitialContext, Java automatically looks for the file jndi.properties on your classpath. You need to create this file in WORKDIR/ etc with settings that match the JBoss server s JNDI registry configuration: java.naming.factory.initial . org.jnp.interfaces.LocalOnlyContextFactory java.naming.factory.url.pkgs org.jboss.naming:org.jnp.interfaces You don t need to know exactly what this configuration means, but it basically points your InitialContext to a JNDI registry running in the local virtual machine (remote EJB client calls would require a JNDI service that supports remote communication). By default, you look up the MessageHandler bean by the name of an implementation class, with the /local suffix for a local interface. How EJBs are named, how they re bound to JNDI, and how you look them up varies and can be customized. These are the defaults for the JBoss server. Finally, you call the MessageHandler EJB and let it do all the work automatically in two units each method call will result in a separate transaction.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

CHAPTER 2 Starting a project There are several

Monday, October 29th, 2007

CHAPTER 2 Starting a project There are several interesting things to observe in this implementation. First, it s a plain Java class with no hard dependencies on any other package. It becomes an EJB only with a single metadata annotation, @Stateless. EJBs support container- managed services, so you can apply the @PersistenceContext annotation, and the server injects a fresh EntityManager instance whenever a method on this stateless bean is called. Each method is also assigned a transaction automatically by the container. The transaction starts when the method is called, and commits when the method returns. (It would be rolled back when an exception is thrown inside the method.) You can now modify the HelloWorld main class and delegate all the work of storing and showing messages to the MessageHandler. Running the application The main class of the Hello World application calls the MessageHandler stateless session bean after looking it up in the JNDI registry. Obviously, the managed environment and the whole application server, including the JNDI registry, must be booted first. You do all of this in the main() method of HelloWorld.java (see listing 2.16). Listing 2.16 Hello World main application code, calling EJBs package hello; import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap; import javax.naming.InitialContext; public class HelloWorld { public static void main(String[] args) throws Exception { // Boot the JBoss Microcontainer with EJB3 settings, automatically // loads ejb3-interceptors-aop.xml and embedded-jboss-beans.xml EJB3StandaloneBootstrap.boot(null); // Deploy custom stateless beans (datasource, mostly) EJB3StandaloneBootstrap .deployXmlResource(”META-INF/helloworld-beans.xml”); // Deploy all EJBs found on classpath (slow, scans all) // EJB3StandaloneBootstrap.scanClasspath(); // Deploy all EJBs found on classpath (fast, scans build directory) // This is a relative location, matching the substring end of one // of java.class.path locations. Print out the value of // System.getProperty(”java.class.path”) to see all paths. EJB3StandaloneBootstrap.scanClasspath(”helloworld-ejb3/bin”); // Create InitialContext from jndi.properties
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Starting a Java Persistence project Every EJB session

Sunday, October 28th, 2007

Starting a Java Persistence project Every EJB session bean needs a business interface. This isn t a special interface that needs to implement predefined methods or extend existing ones; it s plain Java. Create the following interface in the WORKDIR/src/hello package: package hello; public interface MessageHandler { public void saveMessages(); public void showMessages(); } A MessageHandler can save and show messages; it s straightforward. The actual EJB implements this business interface, which is by default considered a local interface (that is, remote EJB clients cannot call it); see listing 2.15. Listing 2.15 The Hello World EJB session bean application code package hello; import javax.ejb.Stateless; import javax.persistence.*; import java.util.List; @Stateless public class MessageHandlerBean implements MessageHandler { @PersistenceContext EntityManager em; public void saveMessages() { Message message = new Message(”Hello World”); em.persist(message); } public void showMessages() { List messages = em.createQuery(”select m from Message m . order by m.text asc”) .getResultList(); System.out.println(messages.size() + ” message(s) found:”); for (Object m : messages) { Message loadedMsg = (Message) m; System.out.println(loadedMsg.getText()); } } }
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Web site construction - CHAPTER 2 Starting a project Also note that

Sunday, October 28th, 2007

CHAPTER 2 Starting a project Also note that we added some line breaks in the property values to make this more readable you shouldn t do this in your real configuration file (unless your database username contains a line break). Configuring the persistence unit Next, you need to change the persistence unit configuration of the Hello World application to access a managed JTA datasource, instead of a resource-local connection pool. Change your WORKDIR/etc/META-INF/persistence.xml file as follows:
java:/HelloWorldDS
You removed many Hibernate configuration options that are no longer relevant, such as the connection pool and database connection settings. Instead, you set a property with the name of the datasource as bound in JNDI. Don t forget that you still need to configure the correct SQL dialect and any other Hibernate options that aren t present in default.persistence.properties. The installation and configuration of the environment is now complete, (we ll show you the purpose of the jndi.properties files in a moment) and you can rewrite the application code with EJBs. Writing EJBs There are many ways to design and create an application with managed components. The Hello World application isn t sophisticated enough to show elaborate examples, so we ll introduce only the most basic type of EJB, a stateless session bean. (You ve already seen entity classes annotated plain Java classes that can have persistent instances. Note that the term entity bean only refers to the old EJB 2.1 entity beans; EJB 3.0 and Java Persistence standardize a lightweight programming model for plain entity classes.)
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Starting a Java Persistence project class=”org.jboss.resource.adapter.jdbc.local.LocalTxDataSource”> java:/HelloWorldDS org.hsqldb.jdbcDriver (Freelance web design)

Saturday, October 27th, 2007

Starting a Java Persistence project class=”org.jboss.resource.adapter.jdbc.local.LocalTxDataSource”>
java:/HelloWorldDS
org.hsqldb.jdbcDriver jdbc:hsqldb:hsql://localhost sa 0 10 1000 100000 Again, the XML header and schema declaration aren t important for this example. You set up two beans: The first is a factory that can produce the second type of bean. The LocalTxDataSource is effectively now your database connection pool, and all your connection pool settings are available on this factory. The factory binds a managed datasource under the JNDI name java:/HelloWorldDS. The second bean configuration declares how the registered object named HelloWorldDS should be instantiated, if another service looks it up in the JNDI registry. Your Hello World application asks for the datasource under this name, and the server calls getDatasource() on the LocalTxDataSource factory to obtain it.
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.