viernes, 9 de octubre de 2009

Conectar a oracle mediante OBDC

Se necesita ejecutar la siguiente instrucción en el server para que se puedan conectar al Oracle 11g mediante ODBC.

alter system set SEC_CASE_SENSITIVE_LOGON=false scope=both sid='*'

martes, 29 de septiembre de 2009

Oracle - Vistas de Diccionarios de datos

V$CIRCUIT

V$CIRCUIT contains information about virtual circuits, which are user connections to the database through dispatchers and servers.

Column Datatype Description
CIRCUIT RAW(4 | 8) Circuit address
DISPATCHER RAW(4 | 8) Current dispatcher process address
SERVER RAW(4 | 8) Current server process address
WAITER RAW(4 | 8) Address of the server process that is waiting for the (currently busy) circuit to become available
SADDR RAW(4 | 8) Address of the session bound to the circuit
STATUS VARCHAR2(16)

Status of the circuit:

  • BREAK - currently interrupted

  • EOF - about to be removed

  • OUTBOUND - an outward link to a remote database

  • NORMAL - normal circuit into the local database

QUEUE NUMBER

Queue the circuit is currently on:

  • COMMON - on the common queue, waiting to be picked up by a server process

  • DISPATCHER - waiting for the dispatcher

  • SERVER - currently being serviced

  • NONE - idle circuit

MESSAGE0 NUMBER Size in bytes of the messages in the first message buffer
MESSAGE1 NUMBER Size in bytes of the messages in the second message buffer
MESSAGE2 NUMBER Size in bytes of the messages in the third message buffer
MESSAGE3 NUMBER Size in bytes of the messages in the fourth message buffer
MESSAGES NUMBER Total number of messages that have gone through this circuit
BYTES NUMBER Total number of bytes that have gone through this circuit
BREAKS NUMBER Total number of breaks (interruptions) for this circuit
PRESENTATION VARCHAR2(257) Presentation protocol used by the client and server
PCIRCUIT RAW(4 | 8) Address of the parent circuit

V$SHARED_SERVER

This view contains information on the shared server processes.

Column Datatype Description
NAME VARCHAR2(4) Name of the server
PADDR RAW(4 | 8) Server's process address
STATUS VARCHAR2(16)

Server status:

EXEC - Executing SQL

WAIT (ENQ) - Waiting for a lock

WAIT (SEND) - Waiting to send data to user

WAIT (COMMON) - Idle; waiting for a user request

WAIT (RESET) - Waiting for a circuit to reset after a break

MESSAGES NUMBER Number of messages processed
BYTES NUMBER Total number of bytes in all messages
BREAKS NUMBER Number of breaks
CIRCUIT RAW(4 | 8) Address of circuit currently being serviced
IDLE NUMBER Total idle time (in hundredths of a second)
BUSY NUMBER Total busy time (in hundredths of a second)
REQUESTS NUMBER Total number of requests taken from the common queue in this server's lifetime

V$DISPATCHER

V$DISPATCHER displays information about the dispatcher processes.

Column Datatype Description
NAME VARCHAR2(4) Name of the dispatcher process
NETWORK VARCHAR2(128) Network address of the dispatcher
PADDR RAW(4 | 8) Process address
STATUS VARCHAR2(16)

Status of the dispatcher:

  • WAIT - Idle

  • SEND - Sending a message

  • RECEIVE - Receiving a message

  • CONNECT - Establishing a connection

  • DISCONNECT - Handling a disconnect request

  • BREAK - Handling a break

  • TERMINATE - In the process of terminating

  • ACCEPT - Accepting connections (no further information available)

  • REFUSE - Rejecting connections (no further information available)

ACCEPT VARCHAR2(3) Indicates whether the dispatcher is accepting new connections (YES) or not (NO)
MESSAGES NUMBER Number of messages processed by the dispatcher
BYTES NUMBER Size (in bytes) of messages processed by the dispatcher
BREAKS NUMBER Number of breaks occurring in the connection
OWNED NUMBER Number of circuits owned by the dispatcher
CREATED NUMBER Number of circuits created by the dispatcher
IDLE NUMBER Total idle time for the dispatcher (in hundredths of a second)
BUSY NUMBER Total busy time for the dispatcher (in hundredths of a second)
LISTENER NUMBER Most recent Oracle error number the dispatcher received from the listener
CONF_INDX NUMBER Zero-based index of the DISPATCHERS configuration used by the dispatcher

V$SHARED_SERVER_MONITOR

This view contains information for tuning the shared server.

Column Datatype Description
MAXIMUM_CONNECTIONS NUMBER Highest number of virtual circuits in use at one time since the instance started. If this value reaches the value set for the CIRCUITS initialization parameter, then consider raising the value of CIRCUITS.
MAXIMUM_SESSIONS NUMBER Highest number of shared server sessions in use at one time since the instance started. If this reaches the value set for the SHARED_SERVER_SESSIONS initialization parameter, then consider raising the value of SHARED_SERVER_SESSIONS.
SERVERS_STARTED NUMBER Total number of shared servers started since the instance started (but not including those started during startup)
SERVERS_TERMINATED NUMBER Total number of shared servers stopped by Oracle since the instance started
SERVERS_HIGHWATER NUMBER Highest number of servers running at one time since the instance started. If this value reaches the value set for the MAX_SHARED_SERVERS initialization parameter, then consider raising the value of SHARED_SERVERS.

V$QUEUE

V$QUEUE contains information on the shared server message queues.

Column Datatype Description
PADDR RAW(4 | 8) Address of the process that owns the queue
TYPE VARCHAR2(10)

Type of queue:

  • COMMON - Processed by servers

  • DISPATCHER

QUEUED NUMBER Number of items in the queue
WAIT NUMBER Total time that all items in this queue have waited (in hundredths of a second). Divide by TOTALQ for average wait per item.
TOTALQ NUMBER Total number of items that have ever been in the queue

viernes, 4 de septiembre de 2009

Como usar Tiles con aplicaciones JavaServerFaces

Lo que se tiene que hacer es agregar el archivo struts.jar de la distribución de los 1.1 de Struts a la ruta de clases. Incluir struts.jar no significa que Struts es necesario para utilizar JSF con Tiles. Es que el paquete se distribuye dentro del archivo struts.jar. No hay otras funcionalidades de la infraestructura de Struts que se trataran.

Algunos consejos útiles.

1.- Aquí está un fragmento del archivo web.xml que habilita Tiles:

<servlet>
   <servlet-name>Faces Servlet</servlet-name>
   <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
   <servlet-name>TilesServet</servlet-name>
   <servlet-class>org.apache.struts.tiles.TilesServlet</servlet-class>
   <init-param>
      <param-name>definitions-config</param-name>
      <param-value>/WEB-INF/tiles-defs.xml</param-value>
   </init-param>
   <load-on-startup>2</load-on-startup>
</servlet>

Pon atención al Tag load-on-startup tag. El servlet Tiles debe ser leído después del server Faces. ¡Esto es importante!

2.- tiles-defs-xml es el nombre del archivo estándar para el archivo de definiciones de Tiles. Sin embargo puedes nombrarlo de la manera que desees y usar mas de uno. Sepáralos por coma para definir tales archivos en el parametro definitions-config en el archivo web.xml.

3.- Establece flush="false" para las etiquetas tiles:insert si los usas dentro de un elemento f:view (entre las etiquetas de inicio y fin de f:view).

4.- Usa la etiqueta f:subview si esta usando tiles dentro de un elemento f:facet, por ejemplo:

<f:facet name="header">
  <f:subview id="header">
    <tiles:insert definition="page.header" flush="false"/>
  </f:subview>
</f:facet>

5.- Nunca incluya un elemento f:view dentro de otro elemento f:view.

6.- No puedes hacer un forward directamente en los Tiles, como en Struts. El archivo faces-config debe referenciar a las paginas usando Tiles como vistas.

jueves, 27 de agosto de 2009

Anotaciones del tutorial: “Using Java Persistence in a Web Application”

http://www.netbeans.org/kb/docs/web/customer-book.html

Coding the Web Application

Development for the Java EE 5 platform is much easier than before because the container does more of the work. Because the container is managing persistence, you do not need to edit any deployment descriptors to configure the CMP mappings or specify the finder methods. In the Java EE 5 platform, persistence is no longer limited to an EJB component. Java EE 5 introduces the Java Persistence API, which can be used by non-EJB components, such as a web application.

Java EE 5 technology also eliminates the need for a lot of the boilerplate code needed in J2EE 1.4 development. EJB development has been streamlined so that fewer interfaces are needed, lookup is simpler, and annotations make component definition and resource injection simple and clear.

Managing Persistence

To manage persistence in the application you only need to create a persistence unit, specify which data source and entity manager to use, and then let the container do the work of managing entities and persistence. The container discovers the entity beans at runtime.

You create a persistence unit by defining it in persistence.xml. The project does not contain a persistence.xml yet so you need to create it. The persistence.xml file is created automatically when you add a persistence unit to the project with the New Persistence Unit wizard. The wizard will help you define the properties of the persistence unit.

TIP: You can also create a persistence unit in the New Entity Class wizard. When creating an entity class, the wizard will prompt you to create a persistence unit if one does not exist.

Creating the Entity Classes

When developing for the J2EE 1.4 platform, when you created entity beans you placed them in an EJB module even when the application was a simple web application. Each entity bean required several interfaces, and you had to configure the deployment descriptors in ejb-jar.xml to define the entity beans, the interfaces, persistence and finder queries for each entity bean.

In Java EE 5, instead of creating entity beans and putting them in the EJB module, you can use simple entity classes, and the entity classes can be placed anywhere in a Java EE 5 application. Writing classes for Java EE 5 applications is also easier than it was for the J2EE 1.4 platform because you can use annotations to define components and inject resources.

@Entity annotation is used to declare the class an entity class. Other annotations provide additional information such as the database table and the columns that the entity class and its properties are mapped to.

Teclas rápidas en Netbeans

  • Ctrl-Shift-N: Nuevo proyecto.
  • Ctrl-Shift-8: Mostrar paleta de componentes.
  • Alt-Shift-F: Dar formato al código.
  • Shift-F6: Ejecutar archivo.
  • Ctrl+S: Guardar cambios.
  • Ctrl-4: IDE’s ouput.
  • Ctrl-5: Ver ventana de servicios.

Anotaciones del tutorial: “Creating a Simple Web Application Using a MySQL Database”

http://www.netbeans.org/kb/docs/web/mysql-webapp.html

Simple web applications can be designed using a two-tier architecture, in which the application communicates directly with a data source using the Java Database Connectivity API. A user's requests are sent to a database, and the results are sent directly back to the user. Two-tier architectures can be easily mapped to a client-server configuration, where a user's browser serves as the client, and a remote database reachable over the Internet corresponds to the server.

The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool.

Setting up a JNDI Datasource

Both GlassFish and Tomcat contain Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. In either case, you need to configure a JNDI Datasource for the server that creates an interface which your application can use for connection pooling. Depending on whether you are using GlassFish or Tomcat, do the following:

GlassFish

The IDE provides enhanced support for GlassFish, enabling you to specify resources using a wizard:

  1. In the Projects window, right-click the Server Resources node and choose New > Other. The New File wizard opens. Under Categories, select GlassFish. Under File Types, select JDBC Resource. Click Next.
  2. Under General Attributes, choose the Create New JDBC Connection Pool option, then in the JNDI Name text field, type in jdbc/IFPWAFCAD. Click Next.
  3. Click Next again to skip Additional Properties, then in Step 4, type in IfpwafcadPool for JDBC Connection Pool Name. Make sure the Extract from Existing Connection option is selected, and choose jdbc:mysql://localhost:3306/MyNewDatabase from the drop-down list. Click Next.
    Note: The wizard detects any database connections that have been set up in the IDE. Therefore, you need to have already created a connection to the MyNewDatabase database at this point. You can verify what connections have been created by opening the Services window (Ctrl-5; ⌘-5 on Mac) and looking for connection nodes ( database connection node icon ) under the Databases category.
  4. Accept any other default settings within the wizard, then click Finish.

By completing the wizard, you declared a new datasource and connection pool for the application. In the Projects window, open the newly created Server Resources > sun-resources.xml file and note that, within the <resources> tags, a jdbc resource and connection pool have been declared containing the values you previously specified.

To confirm that a new datasource and connection pool are indeed registered with GlassFish, you can deploy the project to the server, then locate the resources in the IDE's Services window:

  1. In the Projects window, right-click the IFPWAFCAD project node and choose Deploy (or Undeploy and Deploy). The server starts up if not already running, and the project is compiled and deployed to it.
  2. Open the Services window (Ctrl-5) and expand the Servers > GlassFish > Resources > JDBC > JDBC Resources and Connection Pools nodes. Note that the new datasource and connection pool are now displayed:
    New datasource and connection pool displayed in Services window
Referencing the Datasource from the Application

You need to reference the JNDI resource you just configured from the web application. To do so, you can create an entry in the application's deployment descriptor (web.xml).

Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed to a specific environment. For example, they are normally used to specify application context parameters and behavioral patterns, security settings, as well as mappings for servlets, filters and listeners.

Do the following to reference the JNDI Datasource in the application's deployment descriptor.

  1. In the Projects window, expand the Web Pages > WEB-INF subfolder and double-click web.xml. A graphical editor for the file displays in the Source Editor.
  2. Click the References tab located along the top of the Source Editor. Expand the Resource References heading, then click Add. The Add Resource Reference dialog opens.
  3. For Resource Name, enter the resource name that you gave when configuring the JNDI Datasource for the server above (jdbc/IFPWAFCAD). The Description field is optional, but you can enter a human-readable description of the resource, e.g., Database for IFPWAFCAD application. Note that the default resource type is javax.sql.DataSource. Leave all fields that are provided by default and click OK. The new resource is added under the Resource References heading:
    New JDBC resource listed in the deployment descriptor
    To verify that the resource is now added to the web.xml file, click the XML tab located along the top of the Source Editor. Notice that the following <resource-ref> tags are now included:
    <resource-ref>
    <description>Database for IFPWAFCAD application</description>
    <res-ref-name>jdbc/IFPWAFCAD</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>




Adding the JSTL Library to the Project's Classpath


In order to make better use of the JSP resources at your disposal, you can make use of the JavaServer Pages Standard Tag Library (JSTL) to access and display data taken from the Logic Layer. This library comes bundled with the IDE. You therefore need to make sure the JSTL library is added to the web project's compilation classpath, then add the relevent taglib directives to each of the JSP pages. This allows the server we are using to identify the tags when it reads them from the JSP pages.



Adding taglib Directives to the JSP Pages


Regardless of what server you are using, you need to add the necessary taglib directives to JSP pages:



<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>



Adding JSP and JSTL Code


Finally, add the code to each page. The pages require that you implement an SQL query that utilizes the JSTL <sql:query> tags and the datasource created earlier in the tutorial.




  1. Add the following SQL query beneath the taglib directives you added in the previous step:

    <sql:query var="subjects" dataSource="jdbc/IFPWAFCAD">
    SELECT subject_id, name FROM Subject
    </sql:query>

    The JSTL <sql:query> tags enable you to use SQL query language directly in a JSP page. A resultset is generated from the query, and the acquired data can then be inserted into the page using an iterator tag (<c:forEach>) from the JSTL core library.


  2. Replace the empty <option> tags in the HTML form with the following iterator (changes in bold):

    <select name="subject_id">
    <c:forEach var="subject" items="${subjects.rows}">
    <option value="${subject.subject_id}">${subject.name}</option>
    </c:forEach>

    </select>

    The forEach tag loops through all id and name values from the generated resultset, and inserts each pair into the HTML option tags. In this manner, the form's drop-down list is populated with data.

Anotaciones del tutorial: “NetBeans IDE Tutorial for Web Applications”

http://www.netbeans.org/kb/docs/web/tutorial-webapps.html

  • Composite View. A design pattern that is used to present information in JSP pages. This design pattern creates an aggregate view from component views. Component views might include dynamic and modular portions of the page. The Composite View design pattern pertains to web application design when you are creating a view from numerous subviews. Complex web pages frequently consist of content derived from various resources. The layout of the page is managed independently of the content of its subviews. For instance, a view might have subviews such as Navigation, Search, Feature Story, and Headline.

    When creating a composite view, you can include static content and dynamic content. Static content might consist of an HTML file. Dynamic content is a fragment of a JSP page. The specific content can be determined at either JSP translation time or at runtime.

  • Front controllers. Components that are responsible for routing incoming requests and enforcing navigation in web applications. For more information on the use of the Front Controller design pattern, see the J2EE Patterns catalog.
  • JSP Pages. Files that are used in web applications to present information to end users and to enable data from end users to flow back to the server. JSP pages must be placed within a web application in order for the JSP pages to be executable within the IDE.
  • Servlets. Java classes that execute within a servlet container, which is typically running within a web server. Servlets are used to do the following:
    • Generate dynamic content.
    • Extend the capabilities of web servers and web-enabled application servers.
    • Interact with web clients (typically a browser application such as Netscape or Internet Explorer) using a request-response paradigm.

A front controller is responsible for routing incoming user requests and can enforce navigation in web applications. A front controller provides a single entry point through which requests for several resources in a web application pass. A front controller can reduce duplication of code in JSP pages, especially in cases where several resources require the same processing.

miércoles, 26 de agosto de 2009

Anotaciones del tutorial: “NetBeans IDE Tutorial for Web Applications”

http://www.netbeans.org/kb/docs/web/tutorial-webapps.html

  • Composite View. A design pattern that is used to present information in JSP pages. This design pattern creates an aggregate view from component views. Component views might include dynamic and modular portions of the page. The Composite View design pattern pertains to web application design when you are creating a view from numerous subviews. Complex web pages frequently consist of content derived from various resources. The layout of the page is managed independently of the content of its subviews. For instance, a view might have subviews such as Navigation, Search, Feature Story, and Headline.

    When creating a composite view, you can include static content and dynamic content. Static content might consist of an HTML file. Dynamic content is a fragment of a JSP page. The specific content can be determined at either JSP translation time or at runtime.

  • Front controllers. Components that are responsible for routing incoming requests and enforcing navigation in web applications. For more information on the use of the Front Controller design pattern, see the J2EE Patterns catalog.
  • JSP Pages. Files that are used in web applications to present information to end users and to enable data from end users to flow back to the server. JSP pages must be placed within a web application in order for the JSP pages to be executable within the IDE.
  • Servlets. Java classes that execute within a servlet container, which is typically running within a web server. Servlets are used to do the following:
    • Generate dynamic content.
    • Extend the capabilities of web servers and web-enabled application servers.
    • Interact with web clients (typically a browser application such as Netscape or Internet Explorer) using a request-response paradigm.

A front controller is responsible for routing incoming user requests and can enforce navigation in web applications. A front controller provides a single entry point through which requests for several resources in a web application pass. A front controller can reduce duplication of code in JSP pages, especially in cases where several resources require the same processing.

miércoles, 19 de agosto de 2009

Drag and drop en Java

Para poder desarrollar Drag and Drop (D&D) en Java 2 se utilizan las clases que estan en el package java.awt.dnd.


En primer lugar se necesita un componente GUI que representa la fuente de los datos de la operacion D&D y que mantenga la asociacion con un objeto java.awt.dnd.DropSource.


En segundo lugar se necesita otro componente GIU que representa el destino de los datos de la operacion D&D y que mantenga la asociacion con un objeto java.awt.dnd.DropTarget.


Finalmente necesitamos un objeto java.awt.datatransfer.Transferable que encapsula los datos transferidos entre los objetos DragSource y DropTarget.





Cuando un objeto Transferable encapsula datos, eso hace disponible en el objeto DropTarget un objeto DataFlavors. Para tranferencias locales en la misma maquina virtual de Java (JVM), Transferable provee una referencia a un objeto.


Cuando invocamos una operacion D&D posiblemente requiramos de varios tipos de acciones D&D. La clase DnDConstants define los tipos de acciones soportadas:



  • ACTION_NONE -- No se toma ninguna accion

  • ACTION_COPY -- Deja los datos en el DragSource intactos

  • ACTION_MOVE -- Los datos en el DragSource se eliminan cuando se completa exitosamente la operacion D&D.

  • ACTION_COPY o ACTION_MOVE -- Se ejecuta en el DragSource la operacion requerida por el DropTarget

  • ACTION_LINK o ACTION_REFERENCE -- Cualquier cambio de datos en la fuente o en el destino se propaga en la otra ubicacion.

Creando un componente draggable (Arrastrable)


Para que un componente pueda actuar como una fuente de una operacion D&D debe asociarse con cinco objetos



  • java.awt.dnd.DragSource

  • java.awt.dnd.DragGestureRecognizer

  • java.awt.dnd.DragGestureListener

  • java.awt.datatransfer.Transferable

  • java.awt.dnd.DragSourceListener


El DragSource

Una forma comun de obtener un objeto DragSource es usando una instancia por JVM. Con el metodo de clase DragSource.getDefaultDragSource obtendremos un objeto compartido DragSource que es usado por el tiempo de vida de la JVM. Otra opcion es proveer un DragSource por cada instancia de una clase Component class. Con esta opcion tu eres definir la implementacion.

El DragGestureRecognizer

Las gestiones que inician la operacion D&D varian dependiendo del componente, plataforma y dispositivo

Por ejemplo en windows las gestiones son las siguientes:

  • Move: Clic con el boton izquierdo del raton
  • Copy: CTRL + Boton izquierdo del raton
  • Link: Shift + Boton izquierdo del raton

Un DragGestureRecognizer encapsula estos detalles de implementacion. The instance method dragSource.crecapsula ateDefaultDragGestureRecognizer() will obtain a recognizer and associate it with a component, action, and DragGestureListener

jueves, 8 de enero de 2009

Introducción a la API de Persistencia de Java

El API de Persistencia de Java es parte de la especificación Java EE 5. Encontrará todo lo que necesita para trabajar con entidades en el paquete javax.persistence. Una de las primeras cosas que necesita es una instancia de EntityManager. Un EntityManager proporciona métodos para iniciar y finalizar las transacciones, para persistir y encontrar entidades en el contexto de persistencia, y fusionar o incluso eliminar esas entidades. Además, una instancia EntityManager puede crear y ejecutar consultas.

Un contexto de persistencia es una agrupación de instancias unicas de entidades que son gestionados por el proveedor de persistencia en tiempo de ejecución. Un término similar es la unidad de persistencia, que es el conjunto de todas las clases de entidad que podría utilizar una aplicación. Una unidad de persistencia define un grupo de entidades mapeadas a una base de datos.

Entidades tienen estados de ciclos de vida en la especificación de la API. Conocer el estado de su ciclo de vida le ayudará a entender los efectos de las operaciones de la API en esas entidades. Los distintos estados se enumeran aquí:
  • Nuevo - Las entidades nuevas son nuevos objetos en su aplicación. Una nueva entidad puede existir en su aplicación, pero el contexto de persistencia todavía no es consciente de la entidad.
  • Gestionado - Las entidades gestionadas son entidades que han persistido o que ya existen en la base de datos. Estas entidades tienen una identidad en el contexto de persistencia.
  • Independiente - Las entidades independientes tienen identidad persistente, pero no son gestionados activamente dentro de un contexto de persistencia.
  • Eliminado - Las entidades eliminadas existen en un contexto de persistencia, pero están programadas para ser retirados o eliminados de ese contexto.

Las próximas secciones describe algunas de las operaciones que se pueden utilizar en las entidades y le dará una idea acerca de cómo mover las entidades a través de los distintos estados del ciclo de vida.

Creacion de una nueva entidad

Desde entidades POJOs, puede crearlas tal como lo haría con cualquier otro objeto. Puede utilizar la palabra clave new para crear nuevas instancias de su clase. Usted crea una nueva entidad Jugador usando la palabra clave new que invoca el constructor de Jugador:

Player p = new Player();

En este punto, puede establecer el nombre del jugador, el número e información relacionada. Asimismo, puede establecer las propiedades con un constructor. Esto es especialmente útil y conveniente cuando utilice las anotaciones de persistencia basadas en campos en lugar de anotaciones basadas en propiedades. Las nuevas entidades aún no están gestionados por algun contexto de persistencia.

Manegador de entidades

Para persistir una nueva entidad necesita una instancia de un EntityManager. Obtener una instancia de EntityManager es fácil, pero es tortuoso en los entornos de escritorio. Necesitará una instancia de EntithyManagerFactory para crear un objeto EntityManager. Tendrá que utilizar la clase Persistence clase para obtener la factoria. La clase Persistence es la clase de arranque utilizada en entornos de Java SE.

El siguiente código muestra cómo crear una instancia EntityManager en un entorno de escritorio Java SE. Desde la instancia EntityManager que representan una unidad de persistencia, debe proporcionar el nombre de la unidad de persistencia. En este ejemplo, Liga es el nombre de la unidad de persistencia. Una vez más, una unidad de persistencia define un conjunto de entidades que son asociadas con una aplicación y que se almacenan en una base de datos. El nombre de la liga se declara en el archivo persistence.xml junto con otras propiedades.


// Create the EntityManager
EntityManagerFactory factory = Persistence.createEntityManagerFactory("league");
EntityManager em = factory.createEntityManager();

Entidades gestionadas

Ahora que tiene un objeto EntityManager, puede utilizarlo para crear las consultas y transacciones en un entorno de escritorio. Antes de guardar las nuevas entidades Jugador y Equipo, debe comenzar una transacción. Durante la operación, use el metodo persist del EntityManager para la gestión de una nueva entidad. Las nuevas entidades se ponen en estado gsetionado cuando son persistidos. Debe dar commit a la transacción para que los cambios se guarden en la base de datos. No es de extrañar que vaya a utilizar los metodos begin y commit para estas operaciones.

El código siguiente muestra cómo puede crear y guardar varios jugadores y asignacion de equipo de tareas - por lo menos como son asignados hasta ahora en la temporada 2007 en el Béisbol de las Grandes Ligas.


public class CreatePlayersAndTeams {

/** Creates a new instance of CreatePlayersAndTeams */
public CreatePlayersAndTeams() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

// Create the EntityManager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("league");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

for(Team team: teams) {
em.persist(team);
}

for(Player player: players) {
player.setTeam(teams[0]);
teams[0].addPlayer(player);
em.persist(player);
}

em.getTransaction().commit();

em.close();
emf.close();
}

private static Player[] players = new Player[] {
// name, number, last quoted statement
new Player("Lowe", "Derek", 23, "The sinker's been good to me."),
new Player("Kent", "Jeff", 12, "I wish I could run faster."),
new Player("Garciaparra", "Nomar", 5, "No, I'm not superstitious at all.")
};

public static Team[] teams = new Team[] {
new Team("Los Angeles Dodgers", "National"),
new Team("San Francisco Giants", "National"),
new Team("Anaheim Angels", "American"),
new Team("Boston Red Sox", "American")
};
}