Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

166
Persistence The java persistence API
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    268
  • download

    8

Transcript of Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Page 1: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Persistence

The java persistence API

Page 2: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A few topics

• Java persistence API

• EJB

• Hibernate

• Spring

Page 3: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The Java Persistence API - A Simpler Programming Model for Entity Persistence

(an artitcle from SUN)• http://java.sun.com/developer/technicalArticles/J2EE/jpa/ article link includes a downloadable

example• https://glassfish-samples.dev.java.net/source/browse/*checkout*/glassfish-samples/ws/javaee5/d

ocs/UserREADME.html contains config and setup for running glassfish /java db samples if you are using glassfish sun app server (which is bundled with netbeans)

• A major enhancement in EJB technology is the addition of the new Java Persistence API, which simplifies the entity persistence model and adds capabilities that were not in EJB 2.1 technology. The Java Persistence API deals with the way relational data is mapped to Java objects ("persistent entities"), the way that these objects are stored in a relational database so that they can be accessed at a later time, and the continued existence of an entity's state even after the application that uses it ends. In addition to simplifying the entity persistence model, the Java Persistence API standardizes object-relational mapping.

• In short, EJB 3.0 is much easier to learn and use than was EJB 2.1, the technology's previous version, and should result in faster development of applications. With the inclusion of the Java Persistence API, EJB 3.0 technology also offers developers an entity programming model that is both easier to use and yet richer.

• The Java Persistence API draws on ideas from leading persistence frameworks and APIs such as Hibernate, Oracle TopLink, and Java Data Objects (JDO), and well as on the earlier EJB container-managed persistence. The Expert Group for the Enterprise JavaBeans 3.0 Specification (JSR 220) has representation from experts in all of these areas as well as from other individuals of note in the persistence community.

Page 4: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

An entity is a Plain Old Java Object (POJO), so no boilerplate is required

• The EJB 2.1 version of the entity bean class implements the javax.ejb.EntityBean interface. In fact, an EJB 2.1 entity bean class must implement this interface to interact with the EJB 2.1 container. Because of that, the bean class must also implement all of the methods in the interface: ejbRemove, ejbActivate, ejbPassivate, ejbLoad, ejbStore, setEntityContext, and unsetEntityContext. The class must implement these callback methods even if it doesn't use them, as is the case for most of these methods in the EJB 2.1 example in Figure 3.

• By comparison, an EJB 3.0 entity class is a simple, nonabstract, concrete class -- a POJO, a class that you can instantiate like any other simple Java technology class, with a new operation. It does not implement javax.ejb.EntityBean or any other container-imposed interface. Because the entity class no longer implements javax.ejb.EntityBean, you are no longer required to implement any callback methods. However, you can still implement callback methods in the entity class if you need them to handle life-cycle events for the entity. Also notice the no-argument public constructor. In EJB 3.0 technology, an entity class must have a no-argument public or protected constructor.

Page 5: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Annotations minimize what needs to be specified

• The @Entity metadata annotation marks the EJB 3.0 class as an entity. EJB 3.0 and the Java Persistence API rely heavily on metadata annotation, a feature that was introduced in J2SE 5.0. An annotation consists of the @ sign preceding an annotation type, sometimes followed by a parenthetical list of element-value pairs. The EJB 3.0 specification defines a variety of annotation types. Some examples are those that specify a bean's type, such as@Stateless; those that specify whether a bean is remotely or locally accessible, such as @Remote and @Local; transaction attributes, such as @TransactionAttribute; and security and method permissions, such as @MethodPermissions, @Unchecked, and @SecurityRoles. The Java Persistence API adds annotations, such as @Entity, that are specific to entities. The reliance on annotations in EJB 3.0 and the Java Persistence API demonstrates a significant design shift.

Page 6: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Defaults make things even easier

• In many cases, the application can use defaults instead of explicit metadata annotation elements. In these cases, you don't have to completely specify a metadata annotation. You can obtain the same result as if you had fully specified the annotation. For example, the @Entity annotation has a name element that is used to specify the name to be used in queries that reference the entity. The name element defaults to the unqualified name of the entity class. So in the code for the Address entity, an annotation of @Entity is enough. There's no need to specify a name in the annotation. These defaults can make annotating entities very simple. In many cases, defaults are assumed when an annotation is not specified. In those cases, the defaults represent the most common specifications. For example, container-managed transaction demarcation -- in which the container, as opposed to the bean, manages the commitment or rollback of a unit of work to a database -- is assumed for an enterprise bean if no annotation is specified. These defaults illustrate the coding-by-exception approach that guides EJB 3.0 technology. The process is simpler for the developer. You need to code only when the default is inadequate.

Page 7: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Persistence declarations are simpler

• In EJB 2.1 technology, you specify which fields of the class need to be persisted in a database by defining public abstract getter and setter methods for those fields and by making specifications in a deployment descriptor -- an approach that many programmers find clumsy and far from intuitive. EJB 3.0 technology does not require these specifications. In essence, persistence is built into an entity. The persistent state of an entity is represented either by its persistent fields or persistent properties.

• Recall that an entity is a POJO. Like a POJO, it can have nonabstract, private instance variables, such as the AddressID variable in the Address class. In the Java Persistence API, an entity can have field-based or property-based access. In field-based access, the persistence provider accesses the state of the entity directly through its instance variables. In property-based access, the persistence provider uses JavaBeans-style get/set accessor methods to access the entity's persistent properties. All fields and properties in the entity are persisted. You can, however, override a field or property's default persistence by marking it with the @Transient annotation or the Java keyword transient.

Page 8: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

No XML descriptor needed to declare persistent fields

• In EJB 2.1 technology, entity bean fields are identified as persistent fields in the bean's deployment descriptor, the ejb-jar.xml, an often large and complex XML file. In addition to coding public accessor methods in the entity bean class, you must specify in the deployment descriptor a cmp-field element for each persistent field. In the Java Persistence API, you no longer need to provide a deployment descriptor, called an XML descriptor in the Java Persistence API, to specify an entity's persistent fields.

Page 9: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Default mappings are used where possible

• In EJB 2.1 technology, you define the mapping between an entity bean's fields and their corresponding database columns in a vendor-specific deployment descriptor, such as sun-ejb-jar.xml. By contrast, the Java Persistence API does not require XML descriptors. Instead, you specify the mappings in the entity class by marking the appropriate persistent field or property accessor method with the @Column annotation. You can, however, take advantage of annotation defaults. If you don't specify an @Column annotation for a specific persistent field or property, a default mapping to a database column of the same name as the field or property name is assumed. Although you don't need to specify XML descriptors, you have the option of using them as an alternative to annotations or to supplement annotations. Using an XML descriptor might be useful in externalizing object-relational mapping information. Also, multiple XML descriptors can be useful in tailoring object-relational mapping information to different databases.

• The Java Persistence API standardizes object-relational mapping, enabling fully portable applications.

• Entity Identity• There are also simplifications in the way primary and composite keys for entities are

specified.

Page 10: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

No XML descriptor needed to specify the primary key

• In EJB 2.1 technology, the primary key for an entity bean -- that is, its unique identifier -- is specified not in the entity bean class but rather in its deployment descriptor. In the Java Persistence API, you don't need to provide an XML descriptor to specify an entity's primary key. Instead, you specify the primary key in the entity class by marking an appropriate persistent field or persistent property with the @Id annotation. You can specify composite keys in two different ways, using an @IdClass annotation or an @EmbeddedId annotation.

Page 11: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Relationship declarations are simpler

• Specifying container-managed relationships in EJB 2.1 technology can be quite complex. If entity bean A has a relationship with entity bean B, you must specify abstract getter and setter methods in entity bean A for the related entity bean B. In addition, you must provide a rather lengthy entry for the relationship in the ejb-jar.xml deployment descriptor. In the Java Persistence API, you specify the relationship as you would for any POJO -- through a reference to the related entity object. In addition, you specify annotations that describe the semantics of the relationship and any database table-related metadata. You do not need an XML descriptor to specify entity relationships.

• Note, however, that unlike in EJB 2.1 with container-managed persistence, the application that uses the Java Persistence API is responsible for managing relationships. For example, unlike EJB 2.1 technology, the Java Persistence API requires the backpointer reference in a bidirectional relationship to be set. Assume entity A has a bidirectional relationship to entity B. In EJB 2.1 technology, all you need to do is set the relationship from A to B -- the underlying persistence implementation is responsible for setting the backpointer reference from B to A. The Java Persistence API requires the references to be set on both sides of the relationship. This means that you have to explicitly call b.setA(a) and a.setB(b).

Page 12: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Annotations specify multiplicity and related information

• You declare the relationships in annotations that reference the related entities. Annotations on the persistent fields and properties specify the multiplicity of a relationship, such as one-to-many or many-to-many, and other information, such as cascade and eager fetching. (By comparison, in EJB 2.1 technology, this information is specified in vendor-specific settings.) For example, the @OneToMany annotation on the getAddresses accessor method in the Customer entity, specifies a one-to-many relationship with the Address entity.

• The Customer entity is the owning side of the relationship. There is no associated annotation in the inverse side of the relationship. So this is a one-to-many unidirectional relationship with the Address entity. The value specified for the cascade element in the annotation specifies that life-cycle operations on the Customer entity must be cascaded to the Address entity, the target of the relationship. In other words, when a Customer instance is made persistent, any Address instances related to the Customer are also made persistent. It also means that if a Customer instance is deleted, the related Address instances are also deleted. The FetchType value specifies eager fetching -- this tells the container to prefetch the associated entities.

• The owning side specifies the mapping• Notice that the many-to-many relationship between the Customer and Subscription entity classes

is specified using a @ManyToMany annotation in both classes and a @JoinTable annotation in the Customer class. Either Customer or Subscription could have been specified as the owning class. In this example, Customer is the owning class, and so the @JoinTable annotation is specified in the that class. The @ManyToMany annotation in the Subscription class refers to the Customer class for mapping information through a mappedBy element. Because this example uses a join table for the relationship, the @JoinTable annotation specifies the foreign key columns of the join tables that map to the primary key columns of the related entities.

Page 13: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Mappings and inheritance• Default mappings are used for relationships where possible• You can take advantage of default mappings to simplify the coding

for relationship mapping even further. If you look at the create.sql file under the setup/sql directory for the Java Persistence Demo, you will see a join table named CUSTOMER_ADDRESS. Notice that no annotations are needed in the Customer entity to specify the mapping of the Customer and Address entities to the columns in the CUSTOMER_ADDRESS table. That's because the table name and join column names are the defaults.

• Inheritance and Polymorphism• An important capability of the Java Persistence API is its support for

inheritance and polymorphism, something that was not available in EJB 2.1. You can map a hierarchy of entities, where one entity subclasses another, to a relational database structure, and submit queries against the base class. The queries are treated polymorphically against the entire hierarchy.

Page 14: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

About Spring (from spring.org)• We believe that: • J2EE should be easier to use • It is best to program to interfaces, rather than classes. Spring

reduces the complexity cost of using interfaces to zero. • JavaBeans offer a great way of configuring applications. • OO design is more important than any implementation technology,

such as J2EE. • Checked exceptions are overused in Java. A platform shouldn't

force you to catch exceptions you're unlikely to be able to recover from.

• Testability is essential, and a platform such as Spring should help make your code easier to test.

• Our philosophy is summarized in Expert One-on-One J2EE Design and Development by Rod Johnson.

Page 15: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Spring

• A tutorial at http://static.springsource.org/spring-ws/sites/1.5/reference/html/tutorial.html

• Spring manages xml messaging creating web services that can be used by soap.

• Soap is an xml-based RMI mechanism.• Recall, XML is text, and so soap uses text

to invoke methods of remote objects and to transfer the “payload” back.

Page 16: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Goals of Spring

• Spring should be a pleasure to use • Your application code should not depend on Spring APIs • Spring should not compete with good existing solutions,

but should foster integration. (For example, JDO, Toplink, and Hibernate are great O/R mapping solutions. We don't need to develop another one.)

• Spring Features• Spring is a layered Java/J2EE application platform,

based on code published in Expert One-on-One J2EE Design and Development by Rod Johnson (Wrox, 2002).

Page 17: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Spring includes

• The most complete lightweight container, providing centralized, automated configuration and wiring of your application objects. The container is non-invasive, capable of assembling a complex system from a set of loosely-coupled components (POJOs) in a consistent and transparent fashion. The container brings agility and leverage, and improves application testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment (J2SE or J2EE).

• A common abstraction layer for transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE environments.

• A JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the amount of code you'll need to write. You'll never need to write another finally block to use JDBC again. The JDBC-oriented exceptions comply to Spring's generic DAO exception hierarchy.

• Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps: in terms of resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply to Spring's generic transaction and DAO exception hierarchies.

Page 18: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Spring, continued• AOP functionality, fully integrated into Spring configuration management. You can AOP-enable

any object managed by Spring, adding aspects such as declarative transaction management. With Spring, you can have declarative transaction management without EJB... even without JTA, if you're using a single database in Tomcat or another web container without JTA support.

• A flexible MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry.

• You can use all of Spring's functionality in any J2EE server, and most of it also in non-managed environments. A central focus of Spring is to allow for reusable business and data access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (web or EJB), standalone applications, test environments, etc without any hassle.

• Spring's layered architecture gives you a lot of flexibility. All its functionality builds on lower levels. So you can e.g. use the JavaBeans configuration management without using the MVC framework or AOP support. But if you use the web MVC framework or AOP support, you'll find they build on the core Spring configuration, so you can apply your knowledge about it immediately.

• Other Spring Projects: Each project focuses on addressing a particular enterprise middleware problem in open-source. See the Spring projects page for more information.

• In brief, Spring allows OOD/OOP programmers to focus on objects, not on the mechanics of database interfaces (connections, queries, and so on).

Page 19: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Hibernate

• This is now in a separate hibernate.ppt

Page 20: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

FirstBean\WEB-INF\classes\thepackage\FirstBean.java

package thepackage;

public class GreeterBean {

public String sayHello() {

return("Hello, World!");

}

}

• Note: The src could actually be in another directory called src, but ultimately the class file will have to be in this directory.

• Use any package name you like

Page 21: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

FirstBean\WEB-INF\web.xml

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application

2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"><web-app></web-app>• Note: there is no servlet so this webapp tag can be empty.• There is a JSP (later slide).

Page 22: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

FirstBean\beanExample.jsp<%@ page language="java" %><html> <head><title>Hello Example</title></head> <body> <jsp:useBean id="greeter" class=“thepackage.GreeterBean"

scope="session"/> <%= greeter.sayHello() %> </body></html>• Note: Jsp and html go in the top level of the webapp directory

structure.• Note: URL in next slide:

localhost:port/webappcontext/jspname.jsp

Page 23: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Drop war file in tomcat\webapps

Page 24: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Classpaths and a war file

• War is a web-archive file.• It must have the appropriate directory structure

and required files.• Create a war using java’s jar (a zip) utility.• First compile the java class. • Then create a war file:

jar –cvf nameofit.war list_of_files_and_dirs• You’ll need all the usual stuff in the classpath. A

cp.bat file and cmd.exe shortcut may be handy.

Page 25: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

SecondBean\WEB-INF\classes\thepackage\NumberBean.java

package thepackage;public class NumberBean { private int integerProperty = 1; public int getIntegerProperty() { return integerProperty; } public void setIntegerProperty(int newInteger) { integerProperty = newInteger; }}• As in previous example, this could actually go in a

separate dir called src, but the class file will need to go in …\classes\thepackage

Page 26: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

SecondBean\beanExample.jsp<%@ page language="java" %><jsp:useBean id="number" class=“packagename.NumberBean"

scope="session"/><html> <head><title>Second Bean Example</title></head><body> JavaBean state starts at <%= number.getIntegerProperty() %> <% number.setIntegerProperty(2); %> <br> JavaBean state is now <%= number.getIntegerProperty() %> </body> </html>

Page 27: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

deployment

• Other directories for this example are the same as the first example.

• Still need to javac the java source file.• A jar command for this example, assuming the

cmd.exe is in the SecondBean directory and classpaths are correctly set:

jar –cvf SecondBean.war beanExample.jsp WEB-INF

• Again drop the war file into tomcat\webapps.

Page 28: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Secondbean example

Page 29: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A batch file to jar and deploy@echo off

set JAVA_HOME=\Program Files\Java\jdk1.6.0_11set TomcatHome=\Tomcat"%JAVA_HOME%\bin\jar.exe" -cvf secondbean.war *.jsp WEB-INFcopy secondbean.war "%TomcatHome%\webapps"pause

Page 30: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A few jsp examples & remarks

• Jsp compile at runtime into servlets.

• Some of my examples were built in tomcat, some in JBoss (a server environment with a tomcat embedded server), some in Netbeans which uses SUN’s app server Glassfish.

• I don’t think there are any beans in the next couple of examples, just jsp.

Page 31: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A jsp with a parameter: order confirm

Page 32: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The order example: empty webapp tag and jsp file

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,

Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app></web-app>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML><HEAD><TITLE>Order Confirmation</TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"></HEAD><BODY><H2>Order Confirmation</H2>Thanks for ordering <I><%=

request.getParameter("title") %></I>!

</BODY></HTML>

Page 33: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Css for this exampleBODY { background-color: #FDF5E6 }A:hover { color: red }H1 { color: #440000; text-align: center; font-family: Arial Black, Arial, Helvetica, sans-serif}H2 { color: #440000; font-family: Arial, Helvetica, sans-serif}H3 { color: #440000; font-family: Arial, Helvetica, sans-serif}UL { margin-top: 0; border-top-width: 0; padding-top: 0}DT { font-weight: bold;}PRE { font-size: 105%;}CODE { font-size: 105%; }.TOC { font-size: 90%; font-weight: bold; font-family: Arial, Helvetica, sans-serif}TH.COLORED { background-color: #FFAD00}TR.COLORED { background-color: #FFAD00}TH.TITLE { background-color: #EF8429; font-size: 28px; font-family: Arial, Helvetica, sans-serif;}

• Remember to build directory structure with WEB-INF containing web.xml. Put jsp and css at top level.

• Jar into a war file. Drop it into webapps of tomcat or in the server/default/deploy directory of JBoss.

Page 34: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A bunch of jsp from the coreservlets text

• Along with an empty web.xml file, the css file from above, I packaged a bunch of the simple jsp examples from coreservlets as a war file and put them in JBoss. An example shown below.

Page 35: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Modification of a simple tutorial

• http://www.netbeans.org/kb/docs/web/quickstart-webapps.html#setting

• This tutorial tells exactly how to build a simple java “bean” application, along with screenshots.

• Recall that a bean is a java class with all getter/setter methods and a default constructor.

• My slides just indicate what I changed in the tutorial.

• The tutorial also uses JSP, Java Server Pages.

Page 36: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Getting info from a form

Page 37: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Response from a jsp named dealwithit

Page 38: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Index.jsp has a form with action=dealwithit.jsp

<body> <h1>Hello World!</h1> <form name="Data Input Form" action="dealwithit.jsp"> Name here<input type="text" name="name" value="Justa" /> GPA now<select name="gpa"> <option value="0.0">0.0</option> <option value="1.0">1.0</option> <option value="2.0">2.0</option> <option value="2.5">2.5 </option> <option value="3.0">3.0</option> <option value="3.5">3.5</option> <option value="4.0">4.0</option> </select> Your age? <input type="text" name="age" value="0" /> Adress entry <input type="text" name="address" value="5 maple St" /> <input type="submit" value="send it in" /> </form> </body>

Page 39: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Dealwithit.jsp accesses bean mybean

<body> <jsp:useBean id="mybean" scope="session"

class="org.mypackage.info.InfoHandler" /> <h1><jsp:setProperty name="mybean" property="*" /> I got your info! Name is <jsp:getProperty name="mybean" property="name" /> Address is <jsp:getProperty name="mybean" property="address" /> GPA is <jsp:getProperty name="mybean" property="gpa" /> Age

is <jsp:getProperty name="mybean" property="age" /> </h1> </body>

Note…where I use property =“*” to indicate ALL properties, a single property (“name” or “age” or whatever) could be specified

Page 40: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A little bit of my java class… a bean

package org.mypackage.info;

/** * * @author HIGGINDM */public class InfoHandler {String name;double gpa;int age;String address; public String getAddress() { return address; }

public void setAddress(String address) { this.address = address; }

Page 41: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A simple serializable beanpackage yourpackagename;import java.beans.*;import java.io.Serializable;import java.io.FileOutputStream;import java.io.ObjectOutputStream;import java.io.FileInputStream;import java.io.ObjectInputStream;public class SerializableBean implements Serializable { private int integerProperty=8; public int getIntegerProperty() { return integerProperty; } public void setIntegerProperty(int newInteger) { integerProperty= newInteger; } public boolean save(Object object, String file_name) { boolean status = true; try{ FileOutputStream fos; ObjectOutputStream oos; fos = new FileOutputStream(file_name); oos = new ObjectOutputStream(fos); oos.writeObject(object); oos.close(); } catch (Exception e) { status = false; System.out.println("Error with saving: " + e.toString()); } return status; } public Object retrieve(String file_name) { Object object = new Object(); try { FileInputStream fis; ObjectInputStream ois; fis = new FileInputStream(file_name); ois = new ObjectInputStream(fis); object = ois.readObject(); ois.close(); } catch (Exception e) { System.out.println("Error with retrieval: " + e.toString()); } return object; }}

Page 42: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

firstPage.jsp gets current values and passes file name for serialization

<%@ page language="java" %> <jsp:useBean id="theBean" class="com.masslight.beans.SerializableBean" scope="page" /> <html> <title>Serialized bean, Page One</title> <body> <br> <%= theBean.getIntegerProperty() %> <% theBean.setIntegerProperty(8+theBean.getIntegerProperty()); %> <br> <%= theBean.getIntegerProperty() %> <% theBean.save(theBean, "theBeanFile.ser"); %> <br> <a href="http://localhost:8080/SerializableBean/secondPage.jsp">click here</a>

</body> </html>

Page 43: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Second page opens file and reads values

<%@ page language="java" %> <jsp:useBean id="saver" class="com.masslight.beans.SerializableBean" scope="session"/>

<html> <title>Serialized bean, Page Two</title> <body> <% com.masslight.beans.SerializableBean anotherBean = (yourpackagename.SerializableBean)saver.retrieve("theBeanFile.ser"); %> <%= anotherBean.getIntegerProperty() %>

<br> <% anotherBean.setIntegerProperty(8+ anotherBean.getIntegerProperty()); %> <%= anotherBean.getIntegerProperty() %>

</body> </html>

Page 44: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Deploying this example

• Empty webapp tag in web.xml in WEB-INF• WEB-INF/classes/yourpackagename/put_class_file_here• Jsp go at top level• Javac *.java• Jar serializablebean and put war file in webapps.

Page 45: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Running serializable bean

Page 46: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

What Are Enterprise JavaBeans?

• Enterprise JavaBeans (EJBs) are a part of the Java 2 Enterprise Edition specifications. EJBs provide developers with a distributed, object-oriented, component-based architecture. Developers commonly use an EJB to represent a business object or a table in a database. Part of an application can be built by creating some EJBs to model the different tables in the database and other EJBs to handle the non-persistent business logic. In terms of the model-view-controller model, EJBs can be used to represent the model portion of an application.

• The EJB Architecture• The basic EJB architecture is composed of an EJB server, EJB

containers, EJB clients, Enterprise JavaBeans, and a helper directory and naming service (such as JNDI). Enterprise JavaBeans reside within an EJB container and EJB containers reside in the EJB server. The client does not directly invoke methods of the EJB, instead the container acts as an intermediary between the EJB and the client.

Page 47: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

architecture• EJB servers: Composed of server software, the EJB server is analogous to the

Object Request Broker (ORB) from the CORBA world. The server provides a way for the client to transact with the EJBs. It also provides naming services.

• EJB containers Located inside the EJB server, the EJB containers provide a means for invoking an EJB’s methods. An EJB client can send a request to invoke a method on an EJB to the EJB container. The EJB container invokes the appropriate method on the EJB. Containers provide support for security, object persistence, resource pooling, and transaction processing.

• EJB clients EJB clients find EJBs through a naming and directory service. The client then sends a message to an EJB container, which determines the EJB method that the client wants to invoke.

• Enterprise JavaBeans Enterprise JavaBeans can be session beans, entity beans, or message-driven beans. We will discuss these more in the next section. EJBs reside within EJB containers.

• Directory service The directory/naming service provides the ability to locate any object registered with the directory/naming service. It provides a mapping between a given name of an entity and, in the case of EJBs, a stub that corresponds to the home interface of an Enterprise JavaBean (this will be discussed later in the chapter).

Page 48: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Types of Enterprise JavaBeans

• Session BeansSession beans are used to represent non-persistent business logic. They almost always have an association with a particular client. If the container is shutdown, the session beans running are lost. Session beans can access and modify persistent data, though entity beans are usually more suitable for working with persistent data.

• Entity BeansIn general, developers use entity beans to represent persistent business logic. Entity beans can be shared amongst multiple clients and persist if the client is destroyed or if the server or container is shutdown. Entity beans commonly represent tables of a database. The properties of a bean class represent the different columns of the table. When an instance of an entity EJB is created, the instance can be thought of as temporarily representing a row in the table.

• Message-driven BeansMessage-driven beans are an added feature of the EJB 2.0 specification. They are not discussed in this chapter. A message-driven bean's primary ability is to execute some section of code upon receiving a receipt from a single client message. They are stateless and therefore non-persistent. Also, message-driven EJBs do not survive the crash of an EJB container.

Page 49: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• Passivation/ActivationAn EJB container can manage its primary memory allocation by passivating and activating the EJBs that it manages. Passivation saves the state of a bean to persistent storage, and swaps it out of memory. Activation is just the opposite of passivation: the state of a bean is restored from persistent storage and is swapped into memory. The processes of passivation and activation apply to stateful session beans and all entity beans. Before the EJB is passivated and after the EJB is activated, the container calls the ejbPassivate() or ejbActivate(), respectively, of the EJB's bean class so that the EJB can perform any necessary setup to handle the EJB's change of state.

• PersistenceStateful session beans and entity beans are persistent. The EJB container or the bean class of the EJB provides the necessary functionality to support the persistence of the bean's state. To save a bean, we can get a javax.ejb.Handle object for the bean by invoking the EJB's getHandle() method. Restoration is accomplished by invoking the getEJBObject() method on the Handle object.

Page 50: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The four basic components of an EJB

• IntroductionThe four main components of an EJB are the home interface, the remote interface, the bean class, and the deployment descriptor.

• The home interfaceThe home interface declares the methods for creating, finding, and destroying instances of EJBs. The methods declared in the home interface must correspond to certain methods implemented in the bean class.

• The remote interfaceThe remote interface declares the methods that contain the EJB's business logic. The methods declared in the remote interface must be implemented in the bean class.

• The bean classThe bean class provides the logic of the bean. It must implement the methods declared in the remote interface and must implement methods corresponding to the methods in the home interface.

• The deployment descriptorThe deployment descriptor is always called ejb-jar.xml.

• The deployment descriptor describes EJB(s) to the EJB container. In this chapter we will be deploying only one EJB at a time, so there will be only one EJB described in each deployment descriptor. With JBoss, the .jar file of a single EJB can be deployed directly to the EJB container. This is the method of deployment that will be taken in this chapter, though normally an EJB would need to be deployed as part of an enterprise application archive (.ear). We will see how to create an .ear file in the next chapter.

• Naming the components of an EJB• If the EJB is named Demo, then the remote interface should be Demo.java, the home interface should be

DemoHome.java, the bean class should be either DemoBean.java or DemoEJB.java. The deployment descriptor should always be ejb-jar.xml.

Page 51: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

naming:

Page 52: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

deployment

Page 53: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A simple jboss example with ant script and servlet

Page 54: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

About this tutorial

• There is a servlet… code in slide later on• There is an ant build script… code in slide later on• There is a directory structure..see screenshot• An ear file is generated by ant script. Put it into the jboss

deploy directory (C:\JBOSS-5\server\default\deploy)• The tutorial was adapted from this site:

http://www.roseindia.net/jboss/buildingwebapplicationwithant.shtml

• Go look at the tutorial for directory structure and files if it isn’t clear

Page 55: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The sevlet running and the example dir showing .ear file

Page 56: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

web.xml in directory build/deploymentdescriptors

• <?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN""http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app><servlet>    <servlet-name>HelloWorld</servlet-name>     <servlet-class>HelloWorld</servlet-class> </servlet> 

<servlet-mapping>      <url-pattern>/servlet/HelloWorld</url-pattern>      <servlet-name>HelloWorld</servlet-name></servlet-mapping>

</web-app>

Page 57: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Index.jsp goes in web directory<%@page language="java" %><html><head><title>Welcome to Jboss tutorial with servlet and jsp</title></head>

<body bgcolor="#FFFFCC">

<p align="center"><font size="6" color="#800000">Welcome to<br>Jboss 3.0 Tutorial</font></p><p align="center"><font color="#000080" size="4">Congralutations you have successfullyinstalled lesson 2 tutorial</font></p><p align="center"><font color="#000080" size="4"><a href="servlet/HelloWorld">Click hereto</a> execute Hello World Servlet.</font></p><p><font size="4">&nbsp;</font></p><p align="center"><font color="#000080"><font size="4">For more tutorials and examples visit</font> </font><font size="4"><a href="http://employees.oneonta.edu/higgindm"><font

color="#000080">http://employees.oneonta.edu/higgindm</font></a></font></p></body></html>

Page 58: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Part of build.xml… goes in root…entirety in slide notes

<?xml version="1.0"?>

<project name="Jboss 3.0 tutorial series" default="all" basedir="."><target name="init"><property name="dirs.base" value="${basedir}"/><property name="classdir" value="${dirs.base}/build/src"/><property name="src" value="${dirs.base}/src"/><property name="web" value="${dirs.base}/web"/><property name="deploymentdescription" value="${dirs.base}/build/deploymentdescriptors"/>

<property name="warFile" value="example2.war"/><property name="earFile" value="example2.ear"/><property name="earDir" value="${dirs.base}/build/ear"/><property name="warDir" value="${dirs.base}/build/war"/><!-- Create Web-inf and classes directories --><mkdir dir="${warDir}/WEB-INF"/><mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories --><mkdir dir="${earDir}/META-INF"/>

</target>

<!-- Main target --><target name="all" depends="init,build,buildWar,buildEar"/>

….

Page 59: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The entire servlet (put this in src dir)

import java.io.*;

import java.text.*;

import java.util.*;

import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World Servlet!</title>"); out.println("</head>"); out.println("<body>"); out.println("<p align=\"center\"><font size=\"5\" color=\"#000080\">Hello World!</font></p>"); out.println("<p align=\"center\"><a href=\"javascript:history.back()\">Go to Home</a></p>"); out.println("</body>"); out.println("</html>"); }}

Page 60: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Run ant and then move .ear file to deploy directory of jboss

Page 61: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

session info servlet example… no beans here, just practice using ant\jboss\ear

• Put servlet in the src directory.

• Servlet code is in the slide notes.

Page 62: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Running servlet from form

Page 63: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Form for sessioninfo servlet<html><form

action="http://localhost:8080/sessioninfo/servlet/SessionInfo" method="get">

enter info<br>name:<input type="text"

name="name">Value:<input type="text"

name="value">Address:<input type="text"

name="address">

INPUT TYPE="SUBMIT" ></form></html>

Page 64: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Sessioninfo directory contains…

• Subdirectories:build, source, web

• File:build.xml (in this slide’s notes)

• Run ant in this directory. Ant will use the build script to generate .ear file.

Page 65: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Sessioninfo\build\deploymentdescriptors\web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN""http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app><servlet> <servlet-name>SessionInfo</servlet-name> <servlet-class>SessionInfo</servlet-class> </servlet>

<servlet-mapping> <servlet-name>SessionInfo</servlet-name>

<url-pattern>/servlet/SessionInfo</url-pattern> </servlet-mapping>

</web-app>

Page 66: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Sessioninfo\build\deploymentdescriptors\application.xml

• <?xml version="1.0" encoding="ISO-8859-1"?>

• <application>• <display-name>SessionInfo</display-name>• <module>• <web>• <web-uri>sessioninfo.war</web-uri>• <context-root>/sessioninfo</context-root>• </web>• </module>• </application>

Page 67: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

…/deploymentdescriptors/jboss-app.xml

<jboss-app>

<loader-repository>

example2:archive=sessioninfo.ear

</loader-repository>

</jboss-app>

Page 68: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A more complicated tutorial for deploying a web app

Page 69: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Accessing mysql from JBoss

• JBoss allows webapps to be deployed as *.ear files in the deploy directory.

• Although JBoss uses tomcat, you do not directly access the webapps in Tomcat.

Page 70: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The servlet goes to mysql and queries table

Page 71: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The JBStudents dir with the servlet in slide notes

Page 72: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Part of ant build…entirety in notes<?xml version="1.0"?><project name="JBStudents Servlet" default="all" basedir="."><target name="init"><property name="dirs.base" value="${basedir}"/><property name="classdir" value="${dirs.base}/build/src"/><property name="src" value="${dirs.base}/src"/><property name="web" value="${dirs.base}/web"/><property name="deploymentdescription" value="${dirs.base}/build/deploymentdescriptors"/>

<property name="warFile" value="jbstudents.war"/><property name="earFile" value="jbstudents.ear"/><property name="earDir" value="${dirs.base}/build/ear"/><property name="warDir" value="${dirs.base}/build/war"/><!-- Create Web-inf and classes directories --><mkdir dir="${warDir}/WEB-INF"/><mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories --><mkdir dir="${earDir}/META-INF"/>

</target>

<!-- Main target --><target name="all" depends="init,build,buildWar,buildEar"/>

<!-- Compile Java Files and store in /build/src directory --><target name="build" ><javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" /></target>….

Page 73: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Using ant

• http://www.roseindia.net/jboss/buildingwebapplicationwithant.html

• This url is pretty good except one mistake.

• Build directories etc as indicated and use ant tool. Deploy servlet in deploy directory of JBoss.

Page 74: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

An XXX-ds.xml file in the deploy directory sets up

the JNDI naming <datasources><local-tx-datasource><!-- This connection pool will be bound into JNDI with the name"java:/MySQLDB" -->

<jndi-name>MySQLDB</jndi-name><connection-url>jdbc:mysql://localhost:3306/test</connection-url><driver-class>com.mysql.jdbc.Driver</driver-class><user-name>root</user-name><password></password>

<min-pool-size>5</min-pool-size>

<max-pool-size>15</max-pool-size>

<!-- Don't allow connections to hang out idle too long,never longer than what wait_timeout is set to on theserver...A few minutes is usually okay here,it depends on your applicationand how much spikey load it will see -->

<idle-timeout-minutes>2</idle-timeout-minutes>

<exception-sorter-class-name>com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter</exception-sorter-class-name> <valid-connection-checker-class-name>com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker</valid-connection-checker-class-name>

</local-tx-datasource></datasources>

Page 75: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

My servlet

• In slide notes

• You’ll need J2EE.jar in your classpath.

• If you hunt around, you can find a download for just the jar file, not the entire Sun WebServer.

Page 76: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Fragment of servlet codeInitialContext ctx=null;try{ctx = new InitialContext();}catch (Exception e){System.out.println("Context Lookup Failed"+ e);}String jndiName="java:/MySQLDB";//Lookup the data sourceDataSource ds = null;try{ds = (DataSource)ctx.lookup(jndiName); // note jndiName = java:/MySQLDB}catch(NamingException e){System.out.println("Couldn't Lookup: " + jndiName+ e);throw new RuntimeException(e);}//Get ConnectionConnection conn=null;try{conn = ds.getConnection();}catch(SQLException e){System.out.println("Couldn't Obtain Connection to Database"+ e);}finally{System.out.println("Connection Open: " + conn.toString());}try{ out.println("<HTML><HEAD><TITLE>Students</TITLE></HEAD>"); out.println("<BODY>");stmt = conn.createStatement(); if (stmt.execute("SELECT NAME, Age,Sex,GPA FROM Students")) \{//rest is about the same…generate html table from resultset

Page 77: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Use ant tool to compile servlet, jar and copy files.

C:\JBStudents>antBuildfile: build.xmlinit:build: [javac] Compiling 1 source file to C:\JBStudents\build\srcbuildWar: [copy] Copying 1 file to C:\JBStudents\build\war\WEB-INF\classes [jar] Building jar: C:\JBStudents\build\ear\jbstudents.warbuildEar: [jar] Building jar: C:\JBStudents\jbstudents.earall:BUILD SUCCESSFULTotal time: 1 second

Page 78: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Open ejb for tomcat

Page 79: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• http://openejb.apache.org/tomcat-detailed-instructions.html

• Download openejb.war from apache• Move to tomcat webapps directory.• Visit http://localhost:8080/openejb/installer• (it does the installation)• Wait… Shutdown and restart tomcat. Revisit that

link to check installation.• Follow directions in installation info at apache as

per link above

Page 80: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

http://openejb.apache.org/

• http://docs.codehaus.org/display/OPENEJB/Tomcat+ObjectFactory

• Setting up paths and files to install and run ejbs

• IMPORTANT: You need to copy the openejb-loader to tomcat/webapps folder.

Page 81: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Maven

• Install maven

• Update path settings for maven

• I found I needed to restart my computer to apply the path settings

Page 82: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Open ejb examples

• http://openejb.apache.org/examples.html

• Many of these examples are based on examples at the site.

Page 83: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Open ejb interface on tomcat

Page 84: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Video tutorial: building stateless bean interacting with servlet in tomcat

• https://mediamill.cla.umn.edu/mediamill/embed/7008

• Although he uses a tool for this, you can build it all with any editor.

• You can deploy in tomcat using the standard directory structure.

• Or, jar the directory stucture as a war file and drop into webapps.

Page 85: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A stateless bean FtoC. Form action is http://localhost:8080/FtoCEJB/FtoC/ with

method GET

Page 86: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A few needed jar files

Page 87: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A cp.bat file• My class path settings:• set CLASSPATH=.;C:\ejb_jar_files\ejb.jar;C:\ejb_jar_files\jndi.jar;C:\

ejb_jar_files\geronimo-ejb.jar;C:\ejb_jar_files\j2ee.jar;c:\FtoCEJB;• These must be on one line. I built a batch file called cp.bat. I used javac on

the command line.• In the structure below, the webapp can be dropped into Tomcat’s webapps

directory.• My directory structure:• FtoCEJB

– -WEB-INF• classes

– mycode» FtoC.class» FtoCServlet.class» FtoCBean.class

• web.xml• lib

– J2ee.jar //I don’t know if this is needed

Page 88: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The interface and a bean which implements it

//FtoCBean a stateless ejbpackage mycode;import javax.ejb.Stateless;@Statelesspublic class FtoCBean implements

FtoC {

public double convert(String s) { return

5.0/9.0*(Double.parseDouble(s)-32);

}}

//FtoC interfacepackage mycode;import javax.ejb.Local;@Localpublic interface FtoC {

public double convert(String s);

}

Page 89: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

FtoCServletpackage mycode;import javax.ejb.EJB;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class FtoCServlet extends HttpServlet { @EJB FtoC bean; protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/plain"); ServletOutputStream out = res.getOutputStream();

String degrees=req.getParameter("degrees"); out.println("Welcome to F to C Converter"); out.println(bean.convert(degrees)+" degrees"); }}

Page 90: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Web.xml<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<servlet> <servlet-name>FtoCServlet</servlet-name> <servlet-class>mycode.FtoCServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>FtoCServlet</servlet-name> <url-pattern>/FtoC/*</url-pattern> </servlet-mapping>

</web-app>

Page 91: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A stateful bean…after 5 visits to IncCounterServlet (left) and 1 visit by

ResetCounterServlet (right)

Page 92: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Web.xml defines 2 servlet mappings

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<servlet> <servlet-name>IncCounterServlet</servlet-name> <servlet-class>mycode.IncCounterServlet</servlet-class> </servlet> <servlet> <servlet-name>ResetCounterServlet</servlet-name> <servlet-class>mycode.ResetCounterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>IncCounterServlet</servlet-name> <url-pattern>/IncCounterServlet/*</url-pattern> </servlet-mapping><servlet-mapping> <servlet-name>ResetCounterServlet</servlet-name> <url-pattern>/ResetCounterServlet/*</url-pattern> </servlet-mapping></web-app>

Page 93: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Remote and local interfaces

package mycode;import javax.ejb.*;@Remotepublic interface

CounterRemote {

public int increment();

public int reset();

}

package mycode;public interface

CounterLocal {

public int increment();

public int reset();

}

Page 94: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A stateful bean to implement the interfaces

package mycode;

import javax.ejb.Stateful;

@Statefulpublic class CounterImpl implements

CounterLocal, CounterRemote {

private int count = 0;

public int increment() { return ++count; }

public int reset() { return (count = 0); }

}

/*one of the servlets- Iomitted package and imports*/

public class IncCounterServlet extends HttpServlet {

@EJB CounterLocal bean;

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

res.setContentType("text/plain"); ServletOutputStream out =

res.getOutputStream();

out.println("Welcome to Bean Counter"); out.println(bean.increment()+" :current

count"); }}

Page 95: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A form for a save-the-quote stateful ejb

Page 96: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Making the quote of the day webapp

• It is easy to convert the counter stateful ejb into quote of the day. Just save a string instead of an integer. Provide a setQuote and getQuote method in the interface and the bean. Have the servlet first call getQuote to show the old quote then call setquote with the form data.

Page 97: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The ejb webapp examples

• You need to run mvn clean install in the directory where build is located in …/src/examples/webapps

• (Note…of course, you’ll need to download apache maven for this, and fix relevant path settings).

• After downloading openejb for tomcat I found this webapps directory at:

• C:\openejb-3.1-src\examples\webapps\ejb-examples• This will generate a directory and war file you can put in

tomcat/webapps. • I found my examples at the following URL after some

fussing:• http://localhost:8080/ejb-examples-1.1/put_name_here/• Look up the (URI) names in the web.xml file.

Page 98: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Building the openejb examples

• After downloading and installing maven2

• Goto C:\openejb-3.1-src\examples\webapps\ejb-examples (or wherever you put it) and run

• mvn clean build

• Copy the .war file in the generated target directory to tomcat webapps.

Page 99: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Examples index.jsp

Page 100: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Here’s runas (RunAsServlet)

Page 101: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Here’s another

Page 102: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Once the install is complete go to localhost:8080/openejb for a list of deployed

beans

Page 103: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Here’s one of my beans…my counter… Note jndi

Page 104: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

links

• http://javanotebook.com/2007/09/28/openejb_3_and_tomcat_6.html

• This site had a nice example and good explanation

Page 105: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

A nice expandable example

• http://javanotebook.com/2007/09/28/openejb_3_and_tomcat_6.html

• War file and source available for download

• Includes classes for customer, order, orderitem, ordermanager, product and a servlet.

• I ran it in tomcat.

Page 106: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Simulates (randomly generates) order information

Page 107: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Netbeans

• Netbeans is a complete builder IDE for java, beans and web app deployment, but also for C/C++, Ruby and PHP.

• The Netbeans v6.5 can be downloaded with Glassfish, a sun server, and a bundled Tomcat server. It also contains the java database Derby.

• Deployment is very easy – a click of a button.

Page 108: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Netbeans deployment

• The first tutorial involves using java persistence in a web app

• You Create java classes and deploy to glassfish server using NetBeans IDE

• Creates beans and jsf and ear files and deploys.

• http://www.netbeans.org/kb/61/javaee/persistence.html#getstarted

Page 109: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• You need to download Netbeans IDE with Glassfish sun server.

• JSF: java server faces for manipulating JSP (java server pages)

• This comes with many sample databases but you can complete this using your MySQL if you have: a database with a couple of tables and you know the user/pw associated with the database.

• Recall, MySQL runs on localhost at port 3306.

Generating hibernate persistence mapping with JSF in Netbeans

Page 110: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

You can follow the hibernate tutorial also for this first project

• Steps:• In Netbeans build a New project with JSF and

hibernate frameworks• To project: Add entity mappings from Database

– (you’ll need to start the db beforehand) and you’ll need to know user/pw.

– Select tables to use and generate persistence classes.

• Add entity mappings for JSF• Run the project

Page 111: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

I am using InstantRails to manage MySQL with phpmyadmin

Page 112: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• Apache must be running to manage phpmyadmin.

• Apache is probably on port 80 but if it is on port 8080 you’ll need to stop it before starting (running/deploying) this project in the glassfish server.

Page 113: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Pick some db with a few tables

Page 114: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Make sure you know the user/pw

Page 115: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Choose new proj java-web/web application in netbeans

Page 116: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

I called my proj SampleDBProj

Page 117: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

settings

• I used glassfish server

• Java EE5

• Left context path as it was

Page 118: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Select JSF and hibernate frameworks, new db connection

Page 119: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Setting db properties…then click finish

Page 120: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Click on project node, add entity classes from database

• Select the datasource (this mysql/db thing)

• Give it a JNDI (java naming directory index) name that is unique

• Select tables of interest

Page 121: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.
Page 122: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Pick package name and <click>create persistence unit

Page 123: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Select hibernate as provider…create…select eager fetch and set

collection…finish

Page 124: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Generate CRUD JSF pages from Entity mappings

• Click on project node… select new…

• JSF pages from entity classes…this will generate CRUD functionality

• I added all tables

Page 125: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Make package names…click finish

Page 126: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Netbeans generates a lot of stuff

Page 127: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Run the project… glassfish will start on port 8080

Page 128: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Subjects CRUD

Page 129: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Spring… a tutorial located athttp://www.netbeans.org/kb/61/web/quickstart-webapps-spring.html

• Introduction to the Spring Framework• This document shows you how to construct a simple web MVC application using the

Spring Framework. The application enables a user to enter her name in a text field, and upon clicking OK, the name is returned and displayed on a second page with a welcome greeting.

• The Spring Framework is a popular open source application framework that can make J2EE development easier. It consists of a container, a framework for managing components, and a set of snap-in services for web user interfaces, transactions, and persistence. A part of the Spring Framework is Spring Web MVC, an extensible MVC framework for creating web applications.

• The IDE provides built-in support for Spring Framework 2.5. Framework libraries are packaged with the IDE and are automatically added to the project classpath when the framework is selected. Configuration settings are provided, such as naming and mapping of the Spring Web MVC DispatcherServlet. The JSTL library is automatically registered. Support for Spring XML bean configuration files is also provided, including the following functionality:

• Code completion. Invoked in Spring XML configuration files for Java classes as well as bean references.

• Navigation. Hyperlinking of Java classes and properties mentioned in Spring bean definitions, as well as hyperlinking to other Spring bean references.

• Refactoring. Renaming of references to Java classes in Spring XML configuration files. For more information on the Spring Framework, visit http://www.springframework.org. For a more fine-

grained explanation of how Spring Framework artifacts behave and interact with other objects in an application, visit the official Spring Framework Reference Documentation, or consult the Spring Framework API.

Page 130: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

HelloSpring

• Choose New Project (Ctrl-Shift-N) from the IDE's File menu. Under Categories select Java Web. (If you are using NetBeans 6.1, select Web.) Under Projects select Web Application. Click Next.

• In Project Name, type in HelloSpring. Click Next. • In Step 3, Server and Settings, select the server

you plan to work with from the Server drop-down list. Leave all other settings at their defaults and click Next.

• In Step 4, the Frameworks panel, select Spring Web MVC 2.5:

Page 131: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Spring MVC framework

Page 132: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• When you select Spring Web MVC 2.5, note that you can configure the name and mapping of the Spring dispatcher servlet under the Configuration tab. If you click the Libraries tab, note that JSTL libraries are by default added to the classpath during project creation.

Click Finish. The IDE creates a project for the entire application, including all metadata, as well as the project's Ant build script which you can inspect from the Files window (Ctrl-2). You can view the template structure from the Projects window (Ctrl-1). Also note that four files open by default in the IDE's Source Editor: dispatcher-servlet.xml, applicationContext.xml, redirect.jsp, and index.jsp.

Page 133: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Run skeleton

Page 134: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Web.xml is generated for you and any URL *.htm maps to Spring’s dispatcher servlet.

just a bit of web.xml:<servlet> <servlet-name>dispatcher</servlet-

name> <servlet-

class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>2</load-on-startup> </servlet>

Page 135: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Opening libraries shows spring libraries

Page 136: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Three beans in dispatcher-servlet.xml handle mvc

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="index.htm">indexController</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <!-- The index controller. --> <bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController" p:viewName="index" /> </beans>

Page 137: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Three beans are defined in this file:

indexController, viewResolver, and urlMapping. • When the DispatcherServlet receives a request that matches *.htm

such as index.htm, it looks for a controller within urlMapping that can accommodate the request. Above, you see that there is a mappings property that links /index.htm to indexController.

• The runtime environment then searches for the definition of a bean named indexController, which is conveniently provided by the skeleton project. Note that indexController extends ParameterizableViewController. This is another class provided by Spring, which simply returns a view. Above, note that p:viewName="index" specifies the logical view name, which is resolved using the viewResolver by prepending /WEB-INF/jsp/ and appending .jsp to it. This allows the runtime to locate the file within the WAR file of the application, and respond with the welcome page view (/WEB-INF/jsp/index.jsp).

Page 138: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Overview of the Application

• The application you create is comprised of two JSP pages (which are named views in Spring Web MVC terminology). The first view contains an HTML form with an input field asking for the user's name. The second view is a page that simply displays a hello message containing the user's name.

• The views are managed by a controller, which receives requests to the application and decides which views to return. It also passes to the views any information that they need to display (this is called a model). This application's controller is named HelloController.

• In a complex web application, the business logic is not contained directly in the controller. Instead, another entity, named a service, is used by the controller whenever it needs to perform business logic. In our application, the business logic is the computation of the hello message, so for this purpose you create a HelloService.

Page 139: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Running this simple spring project

Page 141: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

other EJB examples

• Customer book at

• http://www.netbeans.org/kb/55/customer-book.html

• NewsApp at

• http://www.netbeans.org/kb/55/ejb30.html

Page 142: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Customer app redone for my sample db with employees

Page 143: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Adding another servlet to this application

Page 144: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Code in processRequest (a method generated by netbeans…this could also be doGet())

Collection<Contactinfo> contacts = findAllContacts(out); if (contacts != null) { Iterator contactIt = contacts.iterator(); while (contactIt.hasNext()) { contact = (Contactinfo) contactIt.next(); out.println("" + contact.getEmail() +

contact.getPhone()+"</br>"); } } else { out.println("Contacts not found."); }

Page 145: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

My method to find contacts using entity manager

public Collection<Contactinfo> findAllContacts(PrintWriter out) { Collection<Contactinfo> x = null; try { Context ctx = (Context) new InitialContext().lookup("java:comp/env"); EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName"); utx.begin(); Query query=em.createQuery("select c from Contactinfo c"); x=(Collection<Contactinfo>)query.getResultList(); // x=(Collection <Contactinfo>)em.find(Contactinfo.class); utx.commit(); } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught",

e); out.println("catch"+e.toString()); throw new RuntimeException(e); } return x; }

Page 146: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The zoo web app from netbeans

Page 147: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Allows new animal and pavilion creation (something wrong with link up)

Page 148: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The customer info servlet

• Uses persistence without a bean and the bundled derby db server.

Page 149: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

NewsApp uses a message bean

Page 150: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Generating a JavaServer Faces CRUD Application from a Database

• http://www.netbeans.org/kb/docs/web/jsf-jpa-crud-wizard.html• In this tutorial, you use the NetBeans IDE to generate and deploy a web application that displays data from a

database. The tutorial demonstrates how to generate a web application with CRUD (Create, Read, Update, Delete) functionality that uses the Java Persistence API (JPA) to manage the database transaction. In the tutorial you first create entity classes based on tables in a database and then create JavaServer Faces (JSF) pages from the entity classes using the JSF Pages from Entity Classes wizard.

• The JSF Pages from Entity Classes wizard enables you to quickly and easily generate JSF pages for working with a database based on the entity classes in your project. The wizard also gives you the option to enable Ajax functionality in the generated JSF pages. The code generated by the wizard has the following features:

• The code is easy to maintain and customize • Handles all relationship types, generated and non-generated IDs, and embedded IDs, including embedded ID

fields that correspond to foreign key columns • Embedded ID fields are shown as read-only where appropriate • Includes required checks to prevent non-nullable column violations and orphan checks to prevent non-nullable

column violations in related entities (by leveraging nullable or optional annotation elements in the entity classes) • Includes checks to verify that the current entity is correct in order to prevent errors if a user deviates from the

normal page flow (for example, when working in multiple browser tabs) • Forgoes per-property code in certain files in case you later need to modify your database schema • Fields can easily be removed from the generated JSPs to simplify customization • Graceful handling of situations when a user attempts to operate on an entity that has been deleted by another

user or attempts to create an entity that already exists • Pages can be styled easily • In addition to generating JSF pages for you, the JSF Pages from Entity Classes wizard incorporates the

functionality of the JPA Controller Classes from Entity Classes wizard. If you want to create JPA controller classes for entity classes but do not want JSF pages generated for you, you can use the JPA Controller Classes from Entity Classes wizard rather than the JSF Pages from Entity Classes wizard.

Page 151: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Creating the Database

• This tutorial uses a consulting agency database called consult. The database is not included when you install the IDE so you need to first create the database to follow this tutorial.

• The consult database was designed to demonstrate the scope of IDE support for handling a variety of database structures. The database is thus not intended as an example of recommended database design or best-practice. Instead, it attempts to incorporate many of the relevant features that are potentially found in a database design. For example, the consult database contains all possible relationship types, composite primary keys, and many different data types. See the tables below for a more detailed overview of the database structure.

Page 152: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Setting up database

• Note. This tutorial uses the JavaDB database server but you can also complete the tutorial using the MySQL database server. To create the database in MySQL, download and extract the mysql-consult.zip archive. The archive contains SQL scripts for creating and populating the consult database. For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.

Page 153: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• Download derby-consult.zip and extract the archive to your local system. When you extract the archive you will see the SQL scripts for creating and populating the database. The archive also has scripts for dropping tables.

• In the Services window, expand the Databases node, right-click the JavaDB node and choose Start Server.

• Right-click the Java DB node and choose Create Database. • Type consult as the Database Name, User Name, and Password in

the Create Java DB dialog. Click OK.

• A new node appears under the Databases node (jdbc:derby://localhost:1527/consult [consult on CONSULT]).

Page 154: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Building the derby consult database from a file –after run sql- check tables

Page 155: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

When creating entity classes from a database, the IDE automatically generates the appropriate code for the

various field types.

• Database TableDescriptionDesign Features• CLIENT A client of the consulting agencyNon-generated, composite primary key

(whose fields do not constitute a foreign key)• CONSULTANTAn employee of the consulting agency whom clients can hire on a

contract basisIncludes a resume field of type LONG VARCHAR• CONSULTANT_STATUS A consultant's status with the consulting agency (for

example, Active and Inactive are possible statuses)Non-generated primary key of type CHAR

• RECRUITERAn employee of the consulting agency responsible for connecting clients and consultants 

• PROJECT A project that a client staffs with consultants of the consulting agencyNon-generated, composite primary key that includes two fields constituting a foreign key to the CLIENT table

• BILLABLE A set of hours worked by a consultant on a project, for which the consulting agency bills the relevant clientIncludes an artifact field of type CLOB

• ADDRESS A client's billing address  • PROJECT_CONSULTANTJoin table indicating which consultants are currently

assigned to which projectsCross-references PROJECT and CONSULTANT, the former having a composite primary key

Page 156: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

entities• EntityRelated EntityRelationship InformationDescription • CLIENT RECRUITER nullable one-to-one with manual editing; nullable one-to-many

if not edited CLIENT has many RECRUITERs and RECRUITER has zero or one CLIENT (if not manually edited)

• CLIENT ADDRESSnon-nullable one-to-oneCLIENT has one ADDRESS and ADDRESS has zero or one CLIENT

• CLIENT PROJECTnon-nullable one-to-many; in a Project entity, the value of the client field is part of the Project's primary keyCLIENT has many PROJECTs and PROJECT has one CLIENT

• CONSULTANT PROJECTmany-to-manyCONSULTANT has many PROJECTs and PROJECT has many CONSULTANTs

• CONSULTANT BILLABLEnon-nullable one-to-manyCONSULTANT has many BILLABLEs and BILLABLE has one CONSULTANT

• CONSULTANT_STATUS CONSULTANTnon-nullable one-to-manyCONSULTANT_STATUS has many CONSULTANTs and CONSULTANT has one CONSULTANT_STATUS

• CONSULTANT RECRUITERnullable one-to-manyCONSULTANT has zero or one RECRUITER and RECRUITER has many CONSULTANTs

• BILLABLE PROJECTnon-nullable one-to-manyBILLABLE has one PROJECT and PROJECT has many BILLABLEs

Page 157: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Generating entity classes from database connection

Page 158: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Creating persistence unit

Page 159: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

• When using the wizard to create entity classes from a database, the IDE examines the relationships between the tables. In the Projects window, if you expand the jpa.entities Source Package node you can see that the IDE generated an entity class for each table except for the PROJECT_CONSULTANT table. The IDE did not create an entity class for PROJECT_CONSULTANT because the table is a join table.

• The IDE also generated two additional classes for the tables with composite primary keys: CLIENT and PROJECT. The primary key classes for these tables (ClientPK.java and ProjectPK.java) have PK appended to the name.

Page 160: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Editing the Entity Classes

• If desired, you can now edit the generated entity classes. In this exercise you will modify the implementations of the toString method in the entity classes. In the Client and Recruiter classes you will also modify the annotations to change the relationship between clients and recruiters from one-to-many to one-to-one. Because a nullable one-to-many relationship already exists between recruiters and consultants, for demonstration purposes in this tutorial you will establish a nullable one-to-one relationship between clients and recruiters.

Page 161: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Generating JSF Pages From Entity Classes

• Now that the entity classes are created, you can create the web interface for displaying and modifying the data. You will use the JSF Pages from Entity Classes wizard to generate JavaServer Faces pages. The code generated by the wizard includes checks based on the annotations in the entity classes. The wizard also gives you the option to enable Ajax functionality in the application by extending the JavaServer Faces technology with Dynamic Faces technology.

• For each entity class the wizard generates the following:• a JPA controller class • a JSF controller class • a JSF converter class • a directory containing four JSP files (Detail.jsp, Edit.jsp, List.jsp, New.jsp) • managed bean elements, converter elements and navigation rules for the entity in

faces-config.xml • The wizard also generates the following classes used by the controller classes:• exception classes used by the JPA controllers • utility classes used by the JSF controllers

Page 162: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Just the index and recruiter items interfaces

Page 163: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

The html editor netbean app athttp://platform.netbeans.org/tutorials/nbm-htmleditor.html

Page 164: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Sample db with hibernate: link ishttp://www.netbeans.org/kb/docs/web/hibernate-jpa.html

Page 165: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Hibernate example with netbeans slide 2

Page 166: Persistence The java persistence API. A few topics Java persistence API EJB Hibernate Spring.

Generated java classes, xml, jsp, jsf and hibernate mapping