Field-based Persistent Objects Based on Field's lasting object
Note: This article is selected from the resin3.0.12 document EJB 3.0 Supports a field-based RELATIONAL Model: Each Java Field Represents A Database Column. The Tutorial Shows The Configuration, Classes, and Client Code for a single-table entity.
EJB3.0 supports a field-based relational model: Each Java field represents a database column. This tutorial introduces the configuration, classes, and customer code applicable to a single entity.
Overview overview
EJB 3.0 provides a Java model for a relational database, focusing on solving that single, specific problem. Earlier EJB versions overgeneralized, trying to support non-relational data, and lost focus and clarity. Other persistent object specifications, like JDO, tried to provide transparent persistence for Java objects and tried to support both object and relational databases. By restricting to relational database mapping, EJB 3.0 can provide powerful Java models and still simplify the specification and its use.
EJB 3.0 provides a Java model for relational databases, locating a single, special issue. The earlier EJB version function is not prominent, and it is trying to support non-relational data to lose targeted and transparent. Other persistent object specifications, like JDO, try to provide transparent persistence for Java objects, and try to support object databases and relational databases. By limiting relational database mapping, EJB 3.0 can provide a powerful Java model and its specifications and use are still simple.
==
A typical project using EJB 3.0 starts planning with the relational database schema and matching the Java model to that schema.This data-driven approach contrasts with a transparent persistent object approach which starts with Java classes and then tries to create storage to match the Java model , an approach more typical of object-oriented databases.While the transparent persistence model may be appropriate for some applications, EJB 3.0 wisely leaves transparent persistence to other products and specifications, and concentrates on the relational database model.
==== A typical project using EJB 3.0, starting to prepare a relational database assembly, and then match the Java model with this component. This method of data-driven method with a method of transparent persistence, that is, starting with a Java class, then trying to create a data store to match this Java model, a more typically target-oriented database method, forming a control. When this transparent persistent model may apply some applications, EJB 3.0 is cleverly abandoned transparent persistent stereotypes, while the whole god concentrates on the relational database model. ==== in A WAY, EJB 3.0 Simply Provides An Extension To SQL Queries, Returning Fully-Populated Java Objects Instead of Just Returning Primitive Values Like Strings.
In some programs, EJB 3.0 only provides an expansion of the SQL query that returns a Fully-Populated Java object replaces only the simple value of only the same string is the same.
In some programs, EJB 3.0 only provides a SQL query extension, that is, a Java object that returns all package replace the SQL query of the SQL query that only returns the same simple value like a string.
That somewhat understates EJB's capabilities since the Java objects are live, updating the database in a object-oriented fashion, and also provides caching. Still, viewing EJB 3.0 as a SQL extension supporting relations and objects is a good starting model.
A bit conservatively, EJB's ability The Since Java object is live, updating a database of object-oriented methods, and also provides a cache.
Observing SQL extended EJB3.0 as a support relationship and object is still a good original model.
The Tutorial Uses "Entity" to Mean a Persistent Object. In EJB 3.0, An Entity Is A Java Class Instance.
The tutorial uses "Entity" to represent a persistent object. In EJB 3.0, an entity is an example of a Java class.
■ Difference between Differences with EJB 2.1 and EJB 2.1
The EJB 3.0 Draft Is Primarily A Process of Remove Features Superfluous To Supporting Persistent Objects.ejb 3.0 The draft process is first to remove the feature of excessive support for persistent objects.
· No Home Interfaces · No HOME interface
· No local interfaces · No local interface
· No instance pooling · No instance pool
· No Special Create Or Remove Methods · There is no special creation or removing method
· No Special Find or SELECT METHODS · There is no special lookup or selection method
· Deployment Descriptor is Optional · Deployment descriptor is optional
EJB 3.0 Relies on JDITIES INNOTAINABLE, SELF-Documenting Way.ejb 3.0 Depending on the JDK 1.5 comment, the entity is configured with a maintenance.
· Only One Java Class Needed Per Table (No Interface Needed) · Each table only needs a Java class (no interface) · Annotation Per Field · Note Each field
· Annotation Directly in Java Class · Direct Notes in the Java class
· Direct Java Instance (No Proxy or Stub Needed) · Direct Java Instance (no proxy or stub)
■ Files in this tutorial ■ File in this tutorial
WEB-INF / Web.xml Web.xml Configuration Web-INF / CLASS / EXAMPLE / COURSE.JAVA THE Course Bean Web-INF / CLASSEES / EXAMPLE / COURSERVLET.JAVA THE COURSESET
■ Database Model ■ Database Model
The tutorial's design begins with its database model. The table is a collection of school courses, each with an assigned teacher. The table has an integer primary key "id" and two string data fields, "course" and "teacher".
The tutorial design begins its data model. Table is a collection of school courses, each course assigns a teacher. Table has a integer key "ID" and two string data fields, "course" and "teacher".
Course.sql create Table EJB3_BASIC_COURSES (ID Integer Primary Key Auto_Increment,
Course Varchar (250), Teacher Varchar (250));
INSERT INTO EJB3_BASIC_COURSES VALUES ('Potions', 'Severus Snape'); Insert Into EJB3_BASIC_COURSES VALUES ('Transfiguration', 'Minerva McGonagall');
To judge the complexity of EJB 3.0, it's useful to compare the EJB Java model to the simplest possible Java model. The simple model has a single class, Course, for the table and three fields for the table's columns. To evaluate the EJB complicated 3.0 Sex, compare the EJB Java model with the easiest possible Java model. The simple model has a separate class Course for the table, and the fields of the three columns for tables.
Minimal Java Model Package EXAMPLE;
Public class course {private int _id; private string _course; private string _teacher;
.
In Theory, a Persistent Object Tool Could Useout More Information, The Source Doesn't Properly Describe the Class Behavior. Theoretically, a lasting object tool can automatically use the smallest class, but there is no more Information, resources cannot fully describe the behavior of classes.
Fortunately, The JDK 1.5 Metadata Annotations CAN Describe The Persistence Information In A Maintainable, Self-Documenting Way. Lucky, JDK 1.5 metadata comment (in a maintainable, self-documenting Way) describes lasting information.
Of course, those annotations might have default values and should be overridable by an optional XML configuration file, but it's necessary to annotate the intended function of the entity in the Java source itself to properly document and validate the Java code.
Of course, those comments may have a default, and should pass overridable, but it's next the java code, but it's nextself to proPriDE, BUTED Function of the Java Code.
Persistent Object Implementation
The Minimal Java Class Needs The Following Annotations to Produce A Maintainable Persistent Object:
A Annotation to Mark The Class As Persistent.
An Annotation Naming The Relational Table for the Class.
An Annotation to Mark The Primary Key and Any Auto-Generation Capability.
Annotations to Mark Each Persistent Field.
Annotations Naming The Column for the Table.
The following code shows the EJB 3.0 annotations for the course entity. As a quick comparison with the minimal Java class shows, EJB 3.0 is close to the simplest possible implementation of the Java model which provides the necessary annotations in the list.
Course.java
Package example;
@ javax.ejb.entity (access = javax.ejb.accriptiontype.field)
@ javax.ejb.table (name = "EJB3_BASIC_COURSE") public class course {
@ javax.ejb.id (generator = javax.ejb.generatorType.Auto) @ javax.ejb.column (name = "id") private int _id;
@ javax.ejb.basic @ javax.ejb.column (name = "course") private string _COURSE
@ javax.ejb.basic @ javax.ejb.column (name = "teacher") private string _teacher;
Public string course () {return_course;}
Public String Teacher () {return_teacher;}}
The example uses the course () and teacher () methods to emphasize that the field accesses to _course and _teacher are live, ie they read and write the database values directly. (Under the covers, Resin uses bytecode enhancement to make this work.) Examples use course () and teacher () methods to emphasize Field access _Course and _Teacher are vivid, they directly read and write database values. (Under The Covers, Resin Uses Bytecode Enhancement To make this work.)
@ENTINTY - MARKING THE CLASS AS PERSISTENT @ Entity - Marking class for lasting
Course Uses the @entity to Mark The Java Class as a field-based Persistent Object.
@ javax.ejb.entity (access = field)
@ Javax.ejb.Entity Declares a java class as an entity bean. @ javax.ejb.Entity declared a Java class as entity bean.
The access = FIELD value means the bean's fields are persistent, as in JDO. Unlike JDO, only the bean itself or its children may access the fields. Other classes must use the bean's methods, like getters or setters, to indirectly access the fields. The Default Access Value Is Property, Meaning Method getters Are Enhanced.
The Access = field value means that the bean's domain is last, like in JDO. Unlike JDO, only Bean self have or its child can access this domain. Other classes must be used to indirect domains using beans, such as getters or setters. The default access value is Property, which means that the method getters are enhanced.
@Table - Naming The Table @ Table - Naming Table @ Javax.ejb.Table Specifies The SQL Database Table Name To BE Used. If @table is unspecified, resin will use the class name as the table name.
@ javax.ejb.Table Specifies the SQL database table name used. If @Table is not specified, RESIN will use the class name as a table name.
@ javax.ejb.table (name = "EJB3_BASIC_COURSE")
@ID - Marking The Primary Key @ ID - Mark Primary Key
.............................
@ javax.ejb.id (generator = auto) @ javax.ejb.column (name = "id") private int _id;
The optional generator = AUTO specifies automatic generation of primary keys when beans are created. The default NONE does not automatically create primary keys. AUTO generates primary keys depending on the database. Postgres, for example, will use a SEQUENCE, while Resin's built-in Database Will Use an auto_increment identity.
Generator = auto option, which means that the primary key is automatically generated when Bean is created. The default NONE does not automatically create the primary key. Auto generates a primary key dependent database. For example, Postgres will use Sequence, and use an automatic increment Identity when RESIN's Built-In database.
The Optional @Column Annotation Specifies The SQL Column Name. The default SQL Column for an @ID IS "ID".
@BASIC - Marking a Persistent Fieldthe @Basic Attribute Marks a Basic Data Column Like a string or integer or double.
@ javax.ejb.basic @ javax.ejb.column (name = "course") private string _COURSE
. @Column - naming the columnThe optional @Column annotation specifies SQL column name For an @Id, the default column name is "ID" For a @Basic field, the default column name is the field name.Under the covers: bytecode enhancementResin. In Practice, this means replacing setting a field with a resin setter and getting a field with a resin getter.
Public string course () {return_course;}
For Example, Resin Would Process The Above Method and Product Something Like:
Public string course () {return__caucho_get_course ();
Client servlet
................
CourseServlet.java
Public class courseServlet Extends httpservlet {private EntityManager_Manager
Public void setentitymanager (entrymanager manager) {_manager = manager;}
Public void service (httpservletRequest Req, httpservletResponse res) throws java.ioException, servletexception {printwriter out = res. max;
Res.SetContentType ("text / html");
Out.println ("
Query Query = _Manager.createQuery ("SELECT O from Course O"); for (Course Course: (List
"); Out.println (" Teacher: " course.teacher () "
"); out.println ("
");}}}
Course Detailscourse: PotionsStructor: Severus Snape
Course: Transfigurationinstructor: Minerva McGonagall
EntityManagerEntityManager is the primary interface for finding, querying, adding and deleting persistent beans It is stored in JNDI at java:. Comp / EntityManager.public void setEntityManager (EntityManager manager) {_manager = manager;}
THE EXAMPLE Uses Dependency Injection To Configure The Entity Manager. The Web.xml Will Find The EntityManager in JNDI AND SET ITIN The Servlet Before Calling The Init ()
Web.xml configuration
Of Course, a servlet can also use jndi directly in its init () Method.
QueryQuery ACTS LIKE A PreparedStatement In JDBC. It Saves a pased SQL Query and Allows for parameters.
Query Query = _Manager.createQuery ("SELECT O from Course O");
The SQL Used for EJB 3.0 IS An Enhanced Database SQL. The Query Can Return Objects Directly ("SELECT O") And It Can Traverse Relations ("O.Next.Data"). In Most Other Respects, IT CAN Be Thought Of As Regular SQL.
List list = query.listresults ();
The Query Returns Its Values with ListResults (). Queries Which Return A Single Value Can Use GetSingleResult ().
Query returns its value with ListResults (). Returns a separate value inquiry might use getsingleresult ().
Resin Configuration
.
WEB-INF / Web.xml
The
The servlet's