alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  
\");\n" " out.println(\"<td>\" + dateFormatter.format(event.getDate()) " "+ \"</td>\");\n" " out.println(\"</tr>\");\n" " }\n" " out.println(\"</table>\");\n" " }\n" " }]]>" msgstr "" #. Tag: para #: tutorial.xml:1052 #, no-c-format msgid "" "Finally, the <literal>store action is dispatched to the " "<literal>createAndStoreEvent() method, which also uses the " "<literal>Session of the current thread:" msgstr "" "Finalmente, la acción <literal>store se despacha al método " "<literal>createAndStoreEvent(), el cual también utiliza la " "<literal>Session del hilo actual:" #. Tag: programlisting #: tutorial.xml:1058 #, no-c-format msgid "" "<![CDATA[ protected void createAndStoreEvent(String title, Date theDate) " "{\n" " Event theEvent = new Event();\n" " theEvent.setTitle(title);\n" " theEvent.setDate(theDate);\n" "\n" " HibernateUtil.getSessionFactory()\n" " .getCurrentSession().save(theEvent);\n" " }]]>" msgstr "" #. Tag: para #: tutorial.xml:1060 #, no-c-format msgid "" "The servlet is now complete. A request to the servlet will be processed in a " "single <literal>Session and Transaction. As " "earlier in the standalone application, Hibernate can automatically bind " "these objects to the current thread of execution. This gives you the freedom " "to layer your code and access the <literal>SessionFactory in any " "way you like. Usually you would use a more sophisticated design and move the " "data access code into data access objects (the DAO pattern). See the " "Hibernate Wiki for more examples." msgstr "" "El servlet se encuentra completo. Un pedido al servlet será procesado en una " "sola <literal>Session y Transaction. Como lo " "vimos antes en la aplicación autónoma, Hibernate puede enlazar " "automáticamente estos objetos al hilo actual de ejecución. Esto le da la " "libertad de utilizar capas en su código y acceder a la " "<literal>SessionFactory de cualquier manera que lo desee. " "Usualmente, usted utilizaría un diseño más sofisticado y movería el código " "de acceso de datos a los objetos de acceso de datos (el patrón DAO). " "Refiérase al Wiki de Hibernate para ver más ejemplos." #. Tag: title #: tutorial.xml:1074 #, no-c-format msgid "Deploying and testing" msgstr "Despliegue y prueba" #. Tag: para #: tutorial.xml:1076 #, no-c-format msgid "" "To deploy this application for testing we must create a Web ARchive (WAR). " "First we must define the WAR descriptor as <filename>src/main/webapp/WEB-INF/" "web.xml</filename>" msgstr "" "Para implementar esta aplicación para prueba debemos crear una Web ARchive " "(WAR). Primero debemos definir el descriptor WAR como <filename>src/main/" "webapp/WEB-INF/web.xml</filename>" #. Tag: programlisting #: tutorial.xml:1082 #, no-c-format msgid "" "<![CDATA[\n" " <servlet-class>org.hibernate.tutorial.web.EventManagerServlet\n" " <url-pattern>/eventmanager\n" " </servlet-mapping>\n" "</web-app>]]>" msgstr "" #. Tag: para #: tutorial.xml:1084 #, no-c-format msgid "" "To build and deploy call <literal>mvn package in your project " "directory and copy the <filename>hibernate-tutorial.war file into " "your Tomcat <filename>webapps directory." msgstr "" "Para construir y desplegar llame a <literal>mvn package en su " "directorio de proyecto y copie el archivo <literal>hibernate-tutorial.warwebapp Tomcat. " #. Tag: para #: tutorial.xml:1091 #, fuzzy, no-c-format msgid "" "If you do not have Tomcat installed, download it from <ulink url=\"http://" "tomcat.apache.org/\"></ulink> and follow the installation instructions. Our " "application requires no changes to the standard Tomcat configuration." msgstr "" "Si no tiene Tomcat instalado, descárguelo de <ulink url=\"http://tomcat." "apache.org/\" /> y siga las instrucciones de instalación. Nuestra aplicación " "no requiere cambios a la configuración estándar de Tomcat." #. Tag: para #: tutorial.xml:1099 #, no-c-format msgid "" "Once deployed and Tomcat is running, access the application at " "<literal>http://localhost:8080/hibernate-tutorial/eventmanager. " "Make sure you watch the Tomcat log to see Hibernate initialize when the " "first request hits your servlet (the static initializer in " "<literal>HibernateUtil is called) and to get the detailed output " "if any exceptions occurs." msgstr "" "Una vez que se encuentre desplegado y que Tomcat esté ejecutando, acceda la " "aplicación en <literal>http://localhost:8080/hibernate-tutorial/" "eventmanager</literal>. Asegúrese de ver el registro de Tomcat para ver a " "Hibernate iniciar cuando llegue el primer pedido a su servlet (se llama al " "inicializador estático en <literal>HibernateUtil) y para obetener " "la salida detallada si ocurre alguna excepción." #. Tag: title #: tutorial.xml:1112 #, no-c-format msgid "Summary" msgstr "Resumen" #. Tag: para #: tutorial.xml:1114 #, no-c-format msgid "" "This tutorial covered the basics of writing a simple standalone Hibernate " "application and a small web application. More tutorials are available from " "the Hibernate <ulink url=\"http://hibernate.org\">website." msgstr "" "Este tutorial abordó los puntos básicos de la escritura de una simple " "aplicación de Hibernate autónoma y una pequeña aplicación web. Encontrará " "más tutoriales en el website de Hibernate <ulink url=\"http://hibernate.org" "\"></ulink>."

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate tutorial.po source code file:

Hibernate example source code file (tutorial.po)

This example Hibernate source code file (tutorial.po) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Hibernate tags/keywords

cdata, cdata, el, hibernate, hibernate, java, maven, sql, tag, tag, the, the, this, you

The Hibernate tutorial.po source code

# translation of tutorial.po to
# Michael H. Smith <mhideo@redhat.com>, 2007.
# Angela Garcia <agarcia@redhat.com>, 2009, 2010.
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
msgid ""
msgstr ""
"Project-Id-Version: tutorial\n"
"Report-Msgid-Bugs-To: http://bugs.kde.org\n"
"POT-Creation-Date: 2010-07-20 21:02+0000\n"
"PO-Revision-Date: 2010-03-15 13:03+1000\n"
"Last-Translator: Angela Garcia <agarcia@redhat.com>\n"
"Language-Team:  <en@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: KBabel 1.11.4\n"

#. Tag: title
#: tutorial.xml:34
#, no-c-format
msgid "Tutorial"
msgstr "Tutorial"

#. Tag: para
#: tutorial.xml:36
#, no-c-format
msgid ""
"Intended for new users, this chapter provides an step-by-step introduction "
"to Hibernate, starting with a simple application using an in-memory "
"database. The tutorial is based on an earlier tutorial developed by Michael "
"Gloegl. All code is contained in the <filename>tutorials/web "
"directory of the project source."
msgstr ""
"Dirigido a los nuevos usuarios, este capítulo brinda una introducción a "
"Hibernate paso por paso, empezando con una aplicación simple usando una base "
"de datos en memoria. Este tutorial se basa en un tutorial anterior que "
"Michael Gloegl desarrolló. Todo el código se encuentra en el directorio "
"<filename>tutorials/web de la fuente del proyecto. "

#. Tag: para
#: tutorial.xml:45
#, no-c-format
msgid ""
"This tutorial expects the user have knowledge of both Java and SQL. If you "
"have a limited knowledge of JAVA or SQL, it is advised that you start with a "
"good introduction to that technology prior to attempting to learn Hibernate."
msgstr ""
"Este tutorial se basa en que el usuario tenga conocimiento de Java y SQL. Si "
"tiene un conocimiento muy limitado de JAVA o SQL, le aconsejamos que empiece "
"con una buena introducción a esta tecnología antes de tratar de aprender "
"sobre Hibernate."

#. Tag: para
#: tutorial.xml:54
#, no-c-format
msgid ""
"The distribution contains another example application under the "
"<filename>tutorial/eg project source directory."
msgstr ""
"La distribución contiene otra aplicación de ejemplo bajo el directorio "
"fuente del proyecto <filename>tutorial/eg."

#. Tag: title
#: tutorial.xml:62
#, no-c-format
msgid "Part 1 - The first Hibernate Application"
msgstr "Parte 1 - La primera aplicación Hibernate"

#. Tag: para
#: tutorial.xml:64
#, no-c-format
msgid ""
"For this example, we will set up a small database application that can store "
"events we want to attend and information about the host(s) of these events."
msgstr ""
"Para este ejemplo, vamos a configurar una aplicación base de datos pequeña "
"que pueda almacenar eventos a los que queremos asistir e información sobre "
"los anfitriones de estos eventos."

#. Tag: para
#: tutorial.xml:70
#, no-c-format
msgid ""
"Although you can use whatever database you feel comfortable using, we will "
"use <ulink url=\"http://hsqldb.org/\">HSQLDB (an in-memory, Java "
"database) to avoid describing installation/setup of any particular database "
"servers."
msgstr ""
"Aunque puede utilizar cualquier base de datos con la que se sienta bien, "
"vamos a usar <ulink url=\"http://hsqldb.org/\">HSQLDB (una base de "
"datos Java en-memoria) para evitar describir la instalación/configuración de "
"cualquier servidor de base de datos en particular."

#. Tag: title
#: tutorial.xml:79
#, no-c-format
msgid "Setup"
msgstr "Configuración"

#. Tag: para
#: tutorial.xml:81
#, no-c-format
msgid ""
"The first thing we need to do is to set up the development environment. We "
"will be using the \"standard layout\" advocated by alot of build tools such "
"as <ulink url=\"http://maven.org\">Maven. Maven, in particular, has "
"a good resource describing this <ulink url=\"http://maven.apache.org/guides/"
"introduction/introduction-to-the-standard-directory-layout.html\">layout</"
"ulink>. As this tutorial is to be a web application, we will be creating and "
"making use of <filename>src/main/java, src/main/"
"resources</filename> and src/main/webapp directories."
msgstr ""
"Lo primero que tenemos que hacer es configurar el entorno de desarrollo. "
"Vamos a utilizar el \"diseño estándar\" apoyado por muchas herramientas de "
"construcción tal como <ulink url=\"http://maven.org\">Maven. Maven, "
"en particular, tiene un buen recurso que describe este <ulink url=\"http://"
"maven.apache.org/guides/introduction/introduction-to-the-standard-directory-"
"layout.html\">diseño</ulink>. Como este tutorial va a ser una aplicación "
"web, vamos a crear y a utilizar los directorios <filename>src/main/javasrc/main/resources y src/main/"
"webapp</filename>."

#. Tag: para
#: tutorial.xml:91
#, no-c-format
msgid ""
"We will be using Maven in this tutorial, taking advantage of its transitive "
"dependency management capabilities as well as the ability of many IDEs to "
"automatically set up a project for us based on the maven descriptor."
msgstr ""
"Vamos a usar Maven en este tutorial, sacando ventaja de sus funcionalidades "
"de administración de dependencias transitivas así como la habilidad de "
"muchos IDEs para configurar automáticamente un proyecto para nosotros con "
"base en el descriptor maven."

#. Tag: programlisting
#: tutorial.xml:97
#, no-c-format
msgid ""
"<![CDATA[\n"
"\n"
"    <groupId>org.hibernate.tutorials\n"
"    <artifactId>hibernate-tutorial\n"
"    <version>1.0.0-SNAPSHOT\n"
"    <name>First Hibernate Tutorial\n"
"\n"
"    <build>\n"
"         <!-- we dont want the version to be part of the generated war file "
"name -->\n"
"         <finalName>${artifactId}\n"
"    </build>\n"
"\n"
"    <dependencies>\n"
"        <dependency>\n"
"            <groupId>org.hibernate\n"
"            <artifactId>hibernate-core\n"
"        </dependency>\n"
"\n"
"        <!-- Because this is a web app, we also have a dependency on the "
"servlet api. -->\n"
"        <dependency>\n"
"            <groupId>javax.servlet\n"
"            <artifactId>servlet-api\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate uses slf4j for logging, for our purposes here use the "
"simple backend -->\n"
"        <dependency>\n"
"            <groupId>org.slf4j\n"
"            <artifactId>slf4j-simple\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate gives you a choice of bytecode providers between "
"cglib and javassist -->\n"
"        <dependency>\n"
"            <groupId>javassist\n"
"            <artifactId>javassist\n"
"        </dependency>\n"
"    </dependencies>\n"
"\n"
"</project>]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:100
#, fuzzy, no-c-format
msgid ""
"It is not a requirement to use Maven. If you wish to use something else to "
"build this tutorial (such as Ant), the layout will remain the same. The only "
"change is that you will need to manually account for all the needed "
"dependencies. If you use something like <ulink url=\"http://ant.apache.org/"
"ivy/\">Ivy</ulink> providing transitive dependency management you would "
"still use the dependencies mentioned below. Otherwise, you'd need to grab "
"<emphasis>all dependencies, both explicit and transitive, and add "
"them to the project's classpath. If working from the Hibernate distribution "
"bundle, this would mean <filename>hibernate3.jar, all artifacts "
"in the <filename>lib/required directory and all files from either "
"the <filename>lib/bytecode/cglib or lib/bytecode/"
"javassist</filename> directory; additionally you will need both the servlet-"
"api jar and one of the slf4j logging backends."
msgstr ""
"No es un requerimiento el uso de Maven. Si desea utilizar alguna otra cosa "
"para construir este tutorial (tal como Ant), el diseño sigue siendo el "
"mismo. El único cambio es que necesitará dar cuenta manualmente por todas "
"las dependencias que se necesitan. Si usa algo como <ulink url=\"http://ant."
"apache.org/ivy/\">Ivy</ulink> para brindar administración de dependencias "
"transitivas todavía utilizaría las dependencias que mencionamos "
"anteriormente. De otra manera, necesitará encontrar <emphasis>todas, todos "
"los artefactos en el directorio <filename>lib/required y todos "
"los archivos del directorio <filename>lib/bytecode/cglib o "
"<filename>lib/bytecode/javassist; además necesitará el servlet-"
"api jar y uno de los backends de registro slf4j."

#. Tag: para
#: tutorial.xml:117
#, no-c-format
msgid ""
"Save this file as <filename>pom.xml in the project root directory."
msgstr ""
"Guarde este archivo como <filename>pom.xml en el directorio raíz "
"del proyecto."

#. Tag: title
#: tutorial.xml:124
#, no-c-format
msgid "The first class"
msgstr "La primera clase"

#. Tag: para
#: tutorial.xml:126
#, no-c-format
msgid ""
"Next, we create a class that represents the event we want to store in the "
"database; it is a simple JavaBean class with some properties:"
msgstr ""
"Luego creamos una clase que representa el evento que queremos almacenar en "
"la base de datos, es una clase JavaBean simple con algunas propiedades:"

#. Tag: programlisting
#: tutorial.xml:131
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.domain;\n"
"\n"
"import java.util.Date;\n"
"\n"
"public class Event {\n"
"    private Long id;\n"
"\n"
"    private String title;\n"
"    private Date date;\n"
"\n"
"    public Event() {}\n"
"\n"
"    public Long getId() {\n"
"        return id;\n"
"    }\n"
"\n"
"    private void setId(Long id) {\n"
"        this.id = id;\n"
"    }\n"
"\n"
"    public Date getDate() {\n"
"        return date;\n"
"    }\n"
"\n"
"    public void setDate(Date date) {\n"
"        this.date = date;\n"
"    }\n"
"\n"
"    public String getTitle() {\n"
"        return title;\n"
"    }\n"
"\n"
"    public void setTitle(String title) {\n"
"        this.title = title;\n"
"    }\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:133
#, no-c-format
msgid ""
"This class uses standard JavaBean naming conventions for property getter and "
"setter methods, as well as private visibility for the fields. Although this "
"is the recommended design, it is not required. Hibernate can also access "
"fields directly, the benefit of accessor methods is robustness for "
"refactoring."
msgstr ""
"Esta clase utiliza convenciones de nombrado estándares de JavaBean para los "
"métodos de propiedades getter y setter así como también visibilidad privada "
"para los campos. Se recomienda este diseño, pero no se exige. Hibernate "
"también puede acceder a los campos directamente, los métodos de acceso "
"benefician la robustez de la refactorización. "

#. Tag: para
#: tutorial.xml:141
#, no-c-format
msgid ""
"The <literal>id property holds a unique identifier value for a "
"particular event. All persistent entity classes (there are less important "
"dependent classes as well) will need such an identifier property if we want "
"to use the full feature set of Hibernate. In fact, most applications, "
"especially web applications, need to distinguish objects by identifier, so "
"you should consider this a feature rather than a limitation. However, we "
"usually do not manipulate the identity of an object, hence the setter method "
"should be private. Only Hibernate will assign identifiers when an object is "
"saved. Hibernate can access public, private, and protected accessor methods, "
"as well as public, private and protected fields directly. The choice is up "
"to you and you can match it to fit your application design."
msgstr ""
"La propiedad <literal>id tiene un valor identificador único para "
"un evento en particular. Todas las clases de entidad persistentes "
"necesitarán tal propiedad identificadora si queremos utilizar el grupo "
"completo de funcionalidades de Hibernate (también algunas clases "
"dependientes menos importantes). De hecho, la mayoría de las aplicaciones "
"(en especial las aplicaciones web) necesitan distinguir los objetos por "
"identificador, así que usted debe tomar esto como una funcionalidad más que "
"una limitación. Sin embargo, usualmente no manipulamos la identidad de un "
"objeto, por lo tanto, el método setter debe ser privado. Sólamente Hibernate "
"asignará identificadores cuando se guarde un objeto. Como se puede ver, "
"Hibernate puede acceder a métodos de acceso públicos, privados y protegidos, "
"así como también a campos directamente públicos, privados y protegidos. "
"Puede escoger y hacer que se ajuste a su diseño de su aplicación."

#. Tag: para
#: tutorial.xml:156
#, no-c-format
msgid ""
"The no-argument constructor is a requirement for all persistent classes; "
"Hibernate has to create objects for you, using Java Reflection. The "
"constructor can be private, however package or public visibility is required "
"for runtime proxy generation and efficient data retrieval without bytecode "
"instrumentation."
msgstr ""
"El constructor sin argumentos es un requerimiento para todas las clases "
"persistentes, Hibernate tiene que crear objetos por usted utilizando Java "
"Reflection. El constructor puede ser privado; sin embargo, se necesita la "
"visibilidad del paquete para generar proxies en tiempo de ejecución y para "
"la recuperación de datos de manera efectiva sin la instrumentación del "
"código byte."

#. Tag: para
#: tutorial.xml:164
#, no-c-format
msgid ""
"Save this file to the <filename>src/main/java/org/hibernate/tutorial/domain"
msgstr ""

#. Tag: para
#: tutorial.xml:187
#, no-c-format
msgid ""
"Hibernate DTD is sophisticated. You can use it for auto-completion of XML "
"mapping elements and attributes in your editor or IDE. Opening up the DTD "
"file in your text editor is the easiest way to get an overview of all "
"elements and attributes, and to view the defaults, as well as some comments. "
"Hibernate will not load the DTD file from the web, but first look it up from "
"the classpath of the application. The DTD file is included in "
"<filename>hibernate-core.jar (it is also included in the "
"<filename>hibernate3.jar, if using the distribution bundle)."
msgstr ""
"El DTD de Hibernate es sofisticado. Puede utilizarlo para autocompletar los "
"elementos y atributos XML de mapeo en su editor o IDE. Abrir el archivo DTD "
"en su editor de texto es la manera más fácil para obtener una sinopsis de "
"todos los elementos y atributos y para ver los valores por defecto, así como "
"algunos de los comentarios. Note que Hibernate no cargará el fichero DTD de "
"la web, sino que primero lo buscará en la ruta de clase de la aplicación. El "
"archivo DTD se encuentra incluido en <filename>hibernate-core.jar "
"(también en <filename>hibernate3.jar si está usando el paquete de "
"la distribución)."

#. Tag: para
#: tutorial.xml:200
#, no-c-format
msgid ""
"We will omit the DTD declaration in future examples to shorten the code. It "
"is, of course, not optional."
msgstr ""
"Omitiremos la declaración de DTD en los ejemplos posteriores para hacer más "
"corto el código. Esto no es opcional."

#. Tag: para
#: tutorial.xml:206
#, no-c-format
msgid ""
"Between the two <literal>hibernate-mapping tags, include a "
"<literal>class element. All persistent entity classes (again, "
"there might be dependent classes later on, which are not first-class "
"entities) need a mapping to a table in the SQL database:"
msgstr ""
"Entre las dos etiquetas <literal>hibernate-mapping, incluya un "
"elemento <literal>class. Todas las clases de entidad persistentes "
"(de nuevo, podrían haber clases dependientes más adelante, las cuales no son "
"entidades de primera clase) necesitan de dicho mapeo en una tabla en la base "
"de datos SQL:"

#. Tag: programlisting
#: tutorial.xml:213
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""

#. Tag: para
#: tutorial.xml:215
#, no-c-format
msgid ""
"So far we have told Hibernate how to persist and load object of class "
"<literal>Event to the table EVENTS. Each "
"instance is now represented by a row in that table. Now we can continue by "
"mapping the unique identifier property to the tables primary key. As we do "
"not want to care about handling this identifier, we configure Hibernate's "
"identifier generation strategy for a surrogate primary key column:"
msgstr ""
"Hasta ahora le hemos dicho a Hibernate cómo persistir y cargar el objeto de "
"clase <literal>Event a la tabla EVENTS. Cada "
"instancia se encuentra representada por una fila en esa tabla. Ahora podemos "
"continuar mapeando la propiedad identificadora única a la clave primaria de "
"la tabla. Ya que no queremos preocuparnos por el manejo de este "
"identificador, configuramos la estrategia de generación del identificador de "
"Hibernate para una columna clave primaria sustituta:"

#. Tag: programlisting
#: tutorial.xml:225
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""

#. Tag: para
#: tutorial.xml:227
#, no-c-format
msgid ""
"The <literal>id element is the declaration of the identifier "
"property. The <literal>name=\"id\" mapping attribute declares the "
"name of the JavaBean property and tells Hibernate to use the <literal>getId()"
"</literal> and setId() methods to access the property. "
"The column attribute tells Hibernate which column of the <literal>EVENTS es la declaración de la propiedad "
"identificadora. El atributo de mapeo <literal>name=\"id\" declara "
"el nombre de la propiedad JavaBean y le dice a Hibernate que utilice los "
"métodos <literal>getId() y setId() para acceder "
"a la propiedad. El atributo columna le dice a Hibernate qué columna de la "
"tabla <literal>EVENTS tiene el valor de la llave principal."

#. Tag: para
#: tutorial.xml:237
#, no-c-format
msgid ""
"The nested <literal>generator element specifies the identifier "
"generation strategy (aka how are identifier values generated?). In this case "
"we choose <literal>native, which offers a level of portability "
"depending on the configured database dialect. Hibernate supports database "
"generated, globally unique, as well as application assigned, identifiers. "
"Identifier value generation is also one of Hibernate's many extension points "
"and you can plugin in your own strategy."
msgstr ""
"El elemento anidado <literal>generator especifica la estrategia de "
"generación del identificador (también conocidos como ¿cómo se generan los "
"valores del identificador?). En este caso escogimos <literal>native is no longer consider the best strategy in terms "
"of portability. for further discussion, see"
msgstr ""
"<literal>native ya no se considera como la mejor estrategia en "
"términos de portabilidad. Para obtener mayor información consulte <xref "
"linkend=\"portability-idgen\" />. "

#. Tag: para
#: tutorial.xml:255
#, no-c-format
msgid ""
"Lastly, we need to tell Hibernate about the remaining entity class "
"properties. By default, no properties of the class are considered persistent:"
msgstr ""
"Por último es necesario decirle a Hibernate sobre las porpiedades de clase "
"de entidad que quedan. Por defecto, ninguna propiedad de la clase se "
"considera persistente:"

#. Tag: programlisting
#: tutorial.xml:261
#, no-c-format
msgid ""
"<![CDATA[\n"
"<hibernate-mapping package=\"org.hibernate.tutorial.domain\">\n"
"\n"
"    <class name=\"Event\" table=\"EVENTS\">\n"
"        <id name=\"id\" column=\"EVENT_ID\">\n"
"            <generator class=\"native\"/>\n"
"        </id>\n"
"        <property name=\"date\" type=\"timestamp\" column=\"EVENT_DATE\"/>\n"
"        <property name=\"title\"/>\n"
"    </class>\n"
"\n"
"</hibernate-mapping>]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:263
#, no-c-format
msgid ""
"Similar to the <literal>id element, the name "
"attribute of the <literal>property element tells Hibernate which "
"getter and setter methods to use. In this case, Hibernate will search for "
"<literal>getDate(), setDate(), getTitle"
"()</literal> and setTitle() methods."
msgstr ""
"Al igual que con el elemento <literal>id, el atributo "
"<literal>name del elemento property le dice a "
"Hibernate que métodos getter y setter utilizar. Así que en este caso, "
"Hibernate buscará los métodos <literal>getDate(), setDate"
"()</literal>, getTitle() y setTitle()."

#. Tag: para
#: tutorial.xml:274
#, no-c-format
msgid ""
"Why does the <literal>date property mapping include the "
"<literal>column attribute, but the title does "
"not? Without the <literal>column attribute, Hibernate by default "
"uses the property name as the column name. This works for <literal>titledate is a reserved keyword in most "
"databases so you will need to map it to a different name."
msgstr ""
"¿Por qué el mapeo de la propiedad <literal>date incluye el "
"atributo <literal>column, pero el de title no? "
"Sin el atributo <literal>column Hibernate utiliza, por defecto, el "
"nombre de propiedad como nombre de la columna. Esto funciona bien para "
"<literal>title. Sin embargo, date es una "
"palabra clave reservada en la mayoría de las bases de datos, así que es "
"mejor que la mapeamos a un nombre diferente."

#. Tag: para
#: tutorial.xml:284
#, no-c-format
msgid ""
"The <literal>title mapping also lacks a type "
"attribute. The types declared and used in the mapping files are not Java "
"data types; they are not SQL database types either. These types are called "
"<emphasis>Hibernate mapping types, converters which can translate "
"from Java to SQL data types and vice versa. Again, Hibernate will try to "
"determine the correct conversion and mapping type itself if the "
"<literal>type attribute is not present in the mapping. In some "
"cases this automatic detection using Reflection on the Java class might not "
"have the default you expect or need. This is the case with the "
"<literal>date property. Hibernate cannot know if the property, "
"which is of <literal>java.util.Date, should map to a SQL "
"<literal>date, timestamp, or time converter."
msgstr ""
"El mapeo de <literal>title carece de un atributo type, convertidores que "
"pueden traducir de tipos de datos de Java a SQL y viceversa. De nuevo, "
"Hibernate tratará de determinar el tipo correcto de conversión y de mapeo "
"por sí mismo si el atributo <literal>type no se encuentra presente "
"en el mapeo. En algunos casos esta detección automática (utilizando "
"Reflection en la clase Java) puede que no tenga lo que usted espera o "
"necesita. Este es el caso de la propiedad <literal>date. Hibernate "
"no puede saber is la propiedad, la cual es de <literal>java.util.Datedate, "
"<literal>timestamp o time de SQL. Por medio de "
"un convertidor <literal>timestamp, mapeamos la propiedad y "
"mantenemos la información completa sobre la hora y fecha."

#. Tag: para
#: tutorial.xml:300
#, no-c-format
msgid ""
"Hibernate makes this mapping type determination using reflection when the "
"mapping files are processed. This can take time and resources, so if startup "
"performance is important you should consider explicitly defining the type to "
"use."
msgstr ""
"Hibernate realiza esta determinación de tipo de mapeo usando reflection "
"cuando se procesan los archivos de mapeo. Esto puede tomar tiempo y recursos "
"así que el rendimiento al arrancar es importante entonces debe considerar el "
"definir explícitamente el tipo a usar."

#. Tag: para
#: tutorial.xml:307
#, no-c-format
msgid ""
"Save this mapping file as <filename>src/main/resources/org/hibernate/"
"tutorial/domain/Event.hbm.xml</filename>."
msgstr ""
"Guarde este archivo de mapeo como <filename>src/main/resources/org/hibernate/"
"tutorial/domain/Event.hbm.xml</filename>."

#. Tag: title
#: tutorial.xml:315
#, no-c-format
msgid "Hibernate configuration"
msgstr "Configuración de Hibernate"

#. Tag: para
#: tutorial.xml:317
#, no-c-format
msgid ""
"At this point, you should have the persistent class and its mapping file in "
"place. It is now time to configure Hibernate. First let's set up HSQLDB to "
"run in \"server mode\""
msgstr ""
"En este momento debe tener la clase persistente y su archivo de mapeo. Ahora "
"debe configurar Hibernate. Primero vamos a configurar HSQLDB para que "
"ejecute en \"modo de servidor\""

#. Tag: para
#: tutorial.xml:324
#, no-c-format
msgid "We do this do that the data remains between runs."
msgstr "Hacemos esto o lo otro y los datos permanecen entre ejecuciones."

#. Tag: para
#: tutorial.xml:329
#, no-c-format
msgid ""
"We will utilize the Maven exec plugin to launch the HSQLDB server by "
"running: <command> mvn exec:java -Dexec.mainClass=\"org.hsqldb.Server\" -"
"Dexec.args=\"-database.0 file:target/data/tutorial\"</command> You will see "
"it start up and bind to a TCP/IP socket; this is where our application will "
"connect later. If you want to start with a fresh database during this "
"tutorial, shutdown HSQLDB, delete all files in the <filename>target/data e inicie HSQLDB de nuevo."

#. Tag: para
#: tutorial.xml:340
#, no-c-format
msgid ""
"Hibernate will be connecting to the database on behalf of your application, "
"so it needs to know how to obtain connections. For this tutorial we will be "
"using a standalone connection pool (as opposed to a <interfacename>javax.sql."
"DataSource</interfacename>). Hibernate comes with support for two third-"
"party open source JDBC connection pools: <ulink url=\"https://sourceforge."
"net/projects/c3p0\">c3p0</ulink> and . However, we will be using the Hibernate built-in "
"connection pool for this tutorial."
msgstr ""
"Hibernate se conectará a la base de datos de parte de su aplicación así que "
"necesita saber cómo obtener conexiones. Para este tutorial vamos a utilizar "
"un pool de conexiones autónomo (opuesto a <interfacename>javax.sql."
"DataSource</interfacename>). Hibernate viene con soporte para dos pools de "
"conexiones JDBC de código abierto de terceros: <ulink url=\"https://"
"sourceforge.net/projects/c3p0\">c3p0</ulink> y . Sin embargo, vamos a utilizar el pool de "
"conexiones incluido de Hibernate para este tutorial."

#. Tag: para
#: tutorial.xml:351
#, no-c-format
msgid ""
"The built-in Hibernate connection pool is in no way intended for production "
"use. It lacks several features found on any decent connection pool."
msgstr ""
"El pool de conexiones de Hibernate no está diseñado para utilizarse en "
"producción. Le faltan varias funcionalidades que se encuentran en cualquier "
"pool de conexiones decente. "

#. Tag: para
#: tutorial.xml:357
#, no-c-format
msgid ""
"For Hibernate's configuration, we can use a simple <literal>hibernate."
"properties</literal> file, a more sophisticated hibernate.cfg.xml simple, un archivo "
"<literal>hibernate.cfg.xml un poco más sofisticado, o incluso una "
"configuración completamente programática. La mayoría de los usuarios "
"prefieren el archivo de configuración XML:"

#. Tag: programlisting
#: tutorial.xml:363
#, no-c-format
msgid ""
"<![CDATA[\n"
"        <property name=\"connection.password\">\n"
"\n"
"        <!-- JDBC connection pool (use the built-in) -->\n"
"        <property name=\"connection.pool_size\">1\n"
"\n"
"        <!-- SQL dialect -->\n"
"        <property name=\"dialect\">org.hibernate.dialect.HSQLDialect\n"
"\n"
"        <!-- Disable the second-level cache  -->\n"
"        <property name=\"cache.provider_class\">org.hibernate.cache."
"NoCacheProvider</property>\n"
"\n"
"        <!-- Echo all executed SQL to stdout -->\n"
"        <property name=\"show_sql\">true\n"
"\n"
"        <!-- Drop and re-create the database schema on startup -->\n"
"        <property name=\"hbm2ddl.auto\">update\n"
"\n"
"        <mapping resource=\"org/hibernate/tutorial/domain/Event.hbm.xml\"/>\n"
"\n"
"    </session-factory>\n"
"\n"
"</hibernate-configuration>]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:366
#, no-c-format
msgid "Notice that this configuration file specifies a different DTD"
msgstr "Observe que este archivo de configuración especifica un DTD diferente"

#. Tag: para
#: tutorial.xml:369
#, no-c-format
msgid ""
"You configure Hibernate's <literal>SessionFactory. SessionFactory "
"is a global factory responsible for a particular database. If you have "
"several databases, for easier startup you should use several <literal><"
"session-factory></literal> configurations in several configuration files."
msgstr ""
"Configure la <literal>SessionFactory de Hibernate. SessionFactory "
"es una fábrica global responsable de una base de datos en particular. Si "
"usted tiene varias bases de datos, para un inicio más fácil utilice varias "
"configuraciones <literal><session-factory> en varios "
"archivos de configuración."

#. Tag: para
#: tutorial.xml:376
#, no-c-format
msgid ""
"The first four <literal>property elements contain the necessary "
"configuration for the JDBC connection. The dialect <literal>property contienen la "
"configuración necesaria para la conexión JDBC. El elemento "
"<literal>property dialecto especifica la variante SQL en "
"particular que Hibernate genera."

#. Tag: para
#: tutorial.xml:383
#, fuzzy, no-c-format
msgid ""
"In most cases, Hibernate is able to properly determine which dialect to use. "
"See <xref linkend=\"portability-dialectresolver\"/> for more information."
msgstr ""
"Hibernate tiene la habilidad de determinar correctamente qué dialecto "
"utilizar en la mayoría de los casos. Consulte <xref linkend=\"portability-"
"dialectresolver\" /> para obtener mayor información."

#. Tag: para
#: tutorial.xml:389
#, no-c-format
msgid ""
"Hibernate's automatic session management for persistence contexts is "
"particularly useful in this context. The <literal>hbm2ddl.auto "
"option turns on automatic generation of database schemas directly into the "
"database. This can also be turned off by removing the configuration option, "
"or redirected to a file with the help of the <literal>SchemaExport "
"Ant task. Finally, add the mapping file(s) for persistent classes to the "
"configuration."
msgstr ""
"La administración de la sesión automática de Hibernate para contextos de "
"persistencia es particularmente útil en este contexto. La opción "
"<literal>hbm2ddl.auto activa la generación automática de los "
"esquemas de la base de datos directamente en la base de datos. Esto se puede "
"desactivar, eliminando la opción de configuración o redirigiéndolo a un "
"archivo con la ayuda de la tarea de Ant <literal>SchemaExport. "
"Finalmente, agregue a la configuración el/los fichero(s) de mapeo para "
"clases persistentes."

#. Tag: para
#: tutorial.xml:398
#, no-c-format
msgid ""
"Save this file as <filename>hibernate.cfg.xml into the "
"<filename>src/main/resources directory."
msgstr ""
"Guarde este archivo como <filename>hibernate.cfg.xml en el "
"directorio <filename>src/main/resources."

#. Tag: title
#: tutorial.xml:406
#, no-c-format
msgid "Building with Maven"
msgstr "Construcción con Maven"

#. Tag: para
#: tutorial.xml:408
#, no-c-format
msgid ""
"We will now build the tutorial with Maven. You will need to have Maven "
"installed; it is available from the <ulink url=\"http://maven.apache.org/"
"download.html\">Maven download page</ulink>. Maven will read the /"
"pom.xml</filename> file we created earlier and know how to perform some "
"basic project tasks. First, lets run the <literal>compile goal to "
"make sure we can compile everything so far:"
msgstr ""
"Ahora vamos a construir el tutorial con Maven. Es necesario que tenga "
"instalado Maven; se encuentra disponible en la <ulink url=\"http://maven."
"apache.org/download.html\">página de descargas Maven</ulink>. Maven leerá el "
"archivo <filename>/pom.xml que creamos anteriormente y sabrá cómo "
"realizar algunas tareas de proyectos básicos. Primero, vamos a ejecutar la "
"meta <literal>compile para asegurarnos de que podemos compilar "
"todo hasta el momento:"

#. Tag: programlisting
#: tutorial.xml:418
#, no-c-format
msgid ""
"<![CDATA[[hibernateTutorial]$ mvn compile\n"
"[INFO] Scanning for projects...\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] Building First Hibernate Tutorial\n"
"[INFO]    task-segment: [compile]\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] [resources:resources]\n"
"[INFO] Using default encoding to copy filtered resources.\n"
"[INFO] [compiler:compile]\n"
"[INFO] Compiling 1 source file to /home/steve/projects/sandbox/"
"hibernateTutorial/target/classes\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] BUILD SUCCESSFUL\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] Total time: 2 seconds\n"
"[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009\n"
"[INFO] Final Memory: 5M/547M\n"
"[INFO] "
"------------------------------------------------------------------------]]>"
msgstr ""

#. Tag: title
#: tutorial.xml:423
#, no-c-format
msgid "Startup and helpers"
msgstr "Inicio y ayudantes"

#. Tag: para
#: tutorial.xml:425
#, no-c-format
msgid ""
"It is time to load and store some <literal>Event objects, but "
"first you have to complete the setup with some infrastructure code. You have "
"to startup Hibernate by building a global <interfacename>org.hibernate."
"SessionFactory</interfacename> object and storing it somewhere for easy "
"access in application code. A <interfacename>org.hibernate.SessionFactoryorg.hibernate.Sessionorg.hibernate.Session is a thread-safe "
"global object that is instantiated once."
msgstr ""
"Es el momento de cargar y almacenar algunos objetos <literal>Event global y "
"almacenarlo en algún lugar de fácil acceso en el código de la aplicación. "
"Una <interfacename>org.hibernate.SessionFactory se utiliza "
"para obtener instancias <interfacename>org.hibernate.Sessionorg.hibernate.Session "
"representa una unidad de trabajo mono-hilo. La <interfacename>org.hibernate."
"SessionFactory</interfacename> es un objeto global seguro entre hilos que se "
"instancia una sóla vez."

#. Tag: para
#: tutorial.xml:439
#, no-c-format
msgid ""
"We will create a <literal>HibernateUtil helper class that takes "
"care of startup and makes accessing the <interfacename>org.hibernate."
"SessionFactory</interfacename> more convenient."
msgstr ""
"Vamos a crear una clase de ayuda <literal>HibernateUtil que se "
"encargue del inicio y haga más práctico el acceso a <interfacename>org."
"hibernate.SessionFactory</interfacename>. "

#. Tag: programlisting
#: tutorial.xml:445
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.util;\n"
"\n"
"import org.hibernate.SessionFactory;\n"
"import org.hibernate.cfg.Configuration;\n"
"\n"
"public class HibernateUtil {\n"
"\n"
"    private static final SessionFactory sessionFactory = buildSessionFactory"
"();\n"
"\n"
"    private static SessionFactory buildSessionFactory() {\n"
"        try {\n"
"            // Create the SessionFactory from hibernate.cfg.xml\n"
"            return new Configuration().configure().buildSessionFactory();\n"
"        }\n"
"        catch (Throwable ex) {\n"
"            // Make sure you log the exception, as it might be swallowed\n"
"            System.err.println(\"Initial SessionFactory creation failed.\" + "
"ex);\n"
"            throw new ExceptionInInitializerError(ex);\n"
"        }\n"
"    }\n"
"\n"
"    public static SessionFactory getSessionFactory() {\n"
"        return sessionFactory;\n"
"    }\n"
"\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:447
#, no-c-format
msgid ""
"Save this code as <filename>src/main/java/org/hibernate/tutorial/util/"
"HibernateUtil.java</filename>"
msgstr ""
"Guarde este código como <filename>src/main/java/org/hibernate/tutorial/util/"
"HibernateUtil.java</filename>"

#. Tag: para
#: tutorial.xml:452
#, no-c-format
msgid ""
"This class not only produces the global <interfacename>org.hibernate."
"SessionFactory</interfacename> reference in its static initializer; it also "
"hides the fact that it uses a static singleton. We might just as well have "
"looked up the <interfacename>org.hibernate.SessionFactory "
"reference from JNDI in an application server or any other location for that "
"matter."
msgstr ""
"Esta clase no sólamente produce la referencia <interfacename>org.hibernate."
"SessionFactory</interfacename> global en su inicializador estático, sino que "
"también esconde el hecho de que utiliza un singleton estático. También puede "
"que busque la  referencia <interfacename>org.hibernate.SessionFactory "
"a name in your configuration, Hibernate will try to bind it to JNDI under "
"that name after it has been built. Another, better option is to use a JMX "
"deployment and let the JMX-capable container instantiate and bind a "
"<literal>HibernateService to JNDI. Such advanced options are "
"discussed later."
msgstr ""
"Si usted le da un nombre a <interfacename>org.hibernate.SessionFactory a "
"JNDI. Más adelante discutiremos estas opciones avanzadas."

#. Tag: para
#: tutorial.xml:470
#, no-c-format
msgid ""
"You now need to configure a logging system. Hibernate uses commons logging "
"and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer "
"Log4j: copy <literal>log4j.properties from the Hibernate "
"distribution in the <literal>etc/ directory to your srchibernate.cfg.xml. If you "
"prefer to have more verbose output than that provided in the example "
"configuration, you can change the settings. By default, only the Hibernate "
"startup message is shown on stdout."
msgstr ""
"Ahora necesita configurar un sistema de registro. Hibernate utiliza "
"registros comunes le da dos opciones: Log4J y registros de JDK 1.4. La "
"mayoría de los desarrolladores prefieren Log4J: copie <literal>log4j."
"properties</literal> de la distribución de Hibernate, se encuentra en el "
"directorio <literal>etc/) a su directorio src, "
"junto a <literal>hibernate.cfg.xml. Si desea tener una salida más "
"verbosa que la que se proporcionó en la configuración del ejemplo entonces "
"puede cambiar su configuración. Por defecto, sólo se muestra el mensaje de "
"inicio de Hibernate en la salida estándar."

#. Tag: para
#: tutorial.xml:480
#, no-c-format
msgid ""
"The tutorial infrastructure is complete and you are now ready to do some "
"real work with Hibernate."
msgstr ""
"La infraestructura del tutorial está completa y estamos listos para hacer un "
"poco de trabajo real con Hibernate."

#. Tag: title
#: tutorial.xml:488
#, no-c-format
msgid "Loading and storing objects"
msgstr "Carga y almacenamiento de objetos"

#. Tag: para
#: tutorial.xml:490
#, fuzzy, no-c-format
msgid ""
"We are now ready to start doing some real work with Hibernate. Let's start "
"by writing an <literal>EventManager class with a main() con un "
"método <literal>main():"

#. Tag: programlisting
#: tutorial.xml:496
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial;\n"
"\n"
"import org.hibernate.Session;\n"
"\n"
"import java.util.*;\n"
"\n"
"import org.hibernate.tutorial.domain.Event;\n"
"import org.hibernate.tutorial.util.HibernateUtil;\n"
"\n"
"public class EventManager {\n"
"\n"
"    public static void main(String[] args) {\n"
"        EventManager mgr = new EventManager();\n"
"\n"
"        if (args[0].equals(\"store\")) {\n"
"            mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"        }\n"
"\n"
"        HibernateUtil.getSessionFactory().close();\n"
"    }\n"
"\n"
"    private void createAndStoreEvent(String title, Date theDate) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Event theEvent = new Event();\n"
"        theEvent.setTitle(title);\n"
"        theEvent.setDate(theDate);\n"
"        session.save(theEvent);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }\n"
"\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:498
#, no-c-format
msgid ""
"In <literal>createAndStoreEvent() we created a new Event on the "
"database."
msgstr ""
"En <literal>createAndStoreEvent() creamos un nuevo objeto "
"<literal>Event y se lo entregamos a Hibernate. En ese momento, "
"Hibernate se encarga de SQL y ejecuta un <literal>INSERT en la "
"base de datos."

#. Tag: para
#: tutorial.xml:505
#, fuzzy, no-c-format
msgid ""
"A <interface>org.hibernate.Session is designed to represent a "
"single unit of work (a single atomic piece of work to be performed). For now "
"we will keep things simple and assume a one-to-one granularity between a "
"Hibernate <interface>org.hibernate.Session and a database "
"transaction. To shield our code from the actual underlying transaction "
"system we use the Hibernate <interfacename>org.hibernate.Transaction está diseñada para "
"representar una sóla unidad de trabajo (una sola parte atómica de trabajo "
"que se va a realizar). Por ahora vamos a mantener las cosas sencillas y "
"vamos a asumir una granularidad de uno a uno entre la <interface>org."
"hibernate.Session</interface> de Hibernate y una transacción de la base "
"datos. Para proteger nuestro código del sistema de transacciones subyacentes "
"utilizamos el API <interfacename>org.hibernate.Transaction "
"de Hibernate. En este caso en particular estamos utilizado una semántica "
"transaccional basada en JDBC pero también puede ejecutarse con JTA. "

#. Tag: para
#: tutorial.xml:518
#, no-c-format
msgid ""
"What does <literal>sessionFactory.getCurrentSession() do? First, "
"you can call it as many times and anywhere you like once you get hold of "
"your <interfacename>org.hibernate.SessionFactory. The "
"<literal>getCurrentSession() method always returns the \"current\" "
"unit of work. Remember that we switched the configuration option for this "
"mechanism to \"thread\" in our <filename>src/main/resources/hibernate.cfg."
"xml</filename>? Due to that setting, the context of a current unit of work "
"is bound to the current Java thread that executes the application."
msgstr ""
"¿Qué hace <literal>sessionFactory.getCurrentSession()? Primero, la "
"puede llamar tantas veces como desee y en donde quiera, una vez consiga su "
"<interfacename>org.hibernate.SessionFactory. El método "
"<literal>getCurrentSession() siempre retorna la unidad de trabajo "
"\"actual\". ¿Recuerda que cambiamos la opción de la configuración de este "
"mecanismo a \"thread\" en <filename>src/main/resources/hibernate.cfg.xml begins when the first call to "
"<literal>getCurrentSession() is made for the current thread. It is "
"then bound by Hibernate to the current thread. When the transaction ends, "
"either through commit or rollback, Hibernate automatically unbinds the "
"<interface>org.hibernate.Session from the thread and closes it "
"for you. If you call <literal>getCurrentSession() again, you get a "
"new <interface>org.hibernate.Session and can start a new unit of "
"work."
msgstr ""
"Una <interface>org.hibernate.Session se inicia cuando se realiza "
"la primera llamada a <literal>getCurrentSession() para el hilo "
"actual. Luego Hibernate la vincula al hilo actual. Cuando termina la "
"transacción, ya sea por medio de guardar o deshacer los cambios, Hibernate "
"desvincula automáticamente la <interface>org.hibernate.Session "
"del hilo y la cierra por usted. Si llama a <literal>getCurrentSession()org.hibernate.Session "
"nueva y obtiene una nueva <interface>org.hibernate.Session "
"unidad de trabajo. "

#. Tag: para
#: tutorial.xml:554
#, no-c-format
msgid ""
"Related to the unit of work scope, should the Hibernate <interface>org."
"hibernate.Session</interface> be used to execute one or several database "
"operations? The above example uses one <interface>org.hibernate.Session is flexible but you "
"should never design your application to use a new Hibernate <interface>org."
"hibernate.Session</interface> for every database "
"operation. Even though it is used in the following examples, consider "
"<emphasis>session-per-operation an anti-pattern. A real web "
"application is shown later in the tutorial which will help illustrate this."
msgstr ""
"En relación con la unidad del campo de trabajo, ¿Se debería utilizar "
"<interface>org.hibernate.Session de Hibernate para ejecutar una "
"o varias operaciones de la base de datos? El ejemplo anterior utiliza una "
"<interface>org.hibernate.Session para una operación. Sin "
"embargo, esto es pura coincidencia; el ejemplo simplemente no es lo "
"suficientemente complicado para mostrar cualquier otro enfoque. El ámbito de "
"una <interface>org.hibernate.Session de Hibernate es flexible "
"pero nunca debe diseñar su aplicación para que utilice una nueva "
"<interface>org.hibernate.Session de Hibernate para "
"<emphasis>cada operación de la base de datos. Aunque lo "
"utilizamos en los siguientes ejemplos, considere la <emphasis>sesión-por-"
"operación</emphasis> como un anti-patrón. Más adelante en este tutorial, se "
"muestra una aplicación web real, lo cual le ayudará a ilustrar esto."

#. Tag: para
#: tutorial.xml:571
#, fuzzy, no-c-format
msgid ""
"See <xref linkend=\"transactions\"/> for more information about transaction "
"handling and demarcation. The previous example also skipped any error "
"handling and rollback."
msgstr ""
"Consulte <xref linkend=\"transactions\" /> para obtener mayor información "
"sobre el manejo de transacciones y la demarcación. En el ejemplo anterior "
"también nos saltamos el manejo de errores y cómo deshacerlos. "

#. Tag: para
#: tutorial.xml:577
#, no-c-format
msgid ""
"To run this, we will make use of the Maven exec plugin to call our class "
"with the necessary classpath setup: <command>mvn exec:java -Dexec.mainClass="
"\"org.hibernate.tutorial.EventManager\" -Dexec.args=\"store\"</command>"
msgstr ""
"Para ejecutar esto, utilizaremos el plugin de ejecución Maven para llamar "
"nuestra clase con la configuración de ruta de clase necesaria: <command>mvn "
"exec:java -Dexec.mainClass=\"org.hibernate.tutorial.EventManager\" -Dexec."
"args=\"store\"</command>"

#. Tag: para
#: tutorial.xml:584
#, no-c-format
msgid "You may need to perform <command>mvn compile first."
msgstr ""
"Es posible que primero necesite realizar <command>mvn compile."

#. Tag: para
#: tutorial.xml:589
#, no-c-format
msgid ""
"You should see Hibernate starting up and, depending on your configuration, "
"lots of log output. Towards the end, the following line will be displayed:"
msgstr ""
"Debe ver que Hibernate inicia y dependiendo de su configuración, también "
"verá bastantes salidas de registro. Al final, verá la siguiente línea:"

#. Tag: programlisting
#: tutorial.xml:594
#, no-c-format
msgid ""
"<![CDATA[[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) "
"values (?, ?, ?)]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:596
#, no-c-format
msgid "This is the <literal>INSERT executed by Hibernate."
msgstr "Este es el <literal>INSERT que Hibernate ejecuta."

#. Tag: para
#: tutorial.xml:600
#, no-c-format
msgid "To list stored events an option is added to the main method:"
msgstr ""
"Para listar los eventos almacenados se agrega una opción al método principal:"

#. Tag: programlisting
#: tutorial.xml:604
#, no-c-format
msgid ""
"<![CDATA[        if (args[0].equals(\"store\")) {\n"
"            mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"        }\n"
"        else if (args[0].equals(\"list\")) {\n"
"            List events = mgr.listEvents();\n"
"            for (int i = 0; i < events.size(); i++) {\n"
"                Event theEvent = (Event) events.get(i);\n"
"                System.out.println(\n"
"                        \"Event: \" + theEvent.getTitle() + \" Time: \" + "
"theEvent.getDate()\n"
"                );\n"
"            }\n"
"        }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:606
#, no-c-format
msgid "A new <literal>listEvents() method is also added:"
msgstr "También agregamos un método <literal>listEvents():"

#. Tag: programlisting
#: tutorial.xml:610
#, no-c-format
msgid ""
"<![CDATA[    private List listEvents() {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"        List result = session.createQuery(\"from Event\").list();\n"
"        session.getTransaction().commit();\n"
"        return result;\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:612
#, fuzzy, no-c-format
msgid ""
"Here, we are using a Hibernate Query Language (HQL) query to load all "
"existing <literal>Event objects from the database. Hibernate will "
"generate the appropriate SQL, send it to the database and populate "
"<literal>Event objects with the data. You can create more complex "
"queries with HQL. See <xref linkend=\"queryhql\"/> for more information."
msgstr ""
"Aquí utilizamos una consulta HQL (Hibernate Query Language) para cargar "
"todos los objetos <literal>Event desde la base de datos. Hibernate "
"generará el SQL apropiado, lo enviará a la base de datos y poblará los "
"objetos <literal>Event con los datos. Puede crear peticiones más "
"complejas con HQL. Consulte <xref linkend=\"queryhql\"/> para obtener mayor "
"información."

#. Tag: para
#: tutorial.xml:620
#, no-c-format
msgid ""
"Now we can call our new functionality, again using the Maven exec plugin: "
"<command>mvn exec:java -Dexec.mainClass=\"org.hibernate.tutorial.EventManager"
"\" -Dexec.args=\"list\"</command>"
msgstr ""
"Ahora podemos llamar nuestra nueva funcionalidad, de nuevo usando el plugin "
"de ejecución Maven: <command>mvn exec:java -Dexec.mainClass=\"org.hibernate."
"tutorial.EventManager\" -Dexec.args=\"list\"</command>"

#. Tag: title
#: tutorial.xml:630
#, no-c-format
msgid "Part 2 - Mapping associations"
msgstr "Part 2 - Mapeo de asociaciones"

#. Tag: para
#: tutorial.xml:632
#, no-c-format
msgid ""
"So far we have mapped a single persistent entity class to a table in "
"isolation. Let's expand on that a bit and add some class associations. We "
"will add people to the application and store a list of events in which they "
"participate."
msgstr ""
"Hasta ahora hemos mapeado una clase de entidad persistente a una tabla "
"aislada. Vamos a construir sobre esto y agregaremos algunas asociaciones de "
"clase. Vamos a agregar personas a la aplicación y vamos a almacenar una "
"lista de eventos en las que participan."

#. Tag: title
#: tutorial.xml:640
#, no-c-format
msgid "Mapping the Person class"
msgstr "Mapeo de la clase Person"

#. Tag: para
#: tutorial.xml:642
#, no-c-format
msgid "The first cut of the <literal>Person class looks like this:"
msgstr "El primer corte de la clase <literal>Person se ve así:"

#. Tag: programlisting
#: tutorial.xml:646
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.domain;\n"
"\n"
"public class Person {\n"
"\n"
"    private Long id;\n"
"    private int age;\n"
"    private String firstname;\n"
"    private String lastname;\n"
"\n"
"    public Person() {}\n"
"\n"
"    // Accessor methods for all properties, private setter for 'id'\n"
"\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:648
#, no-c-format
msgid ""
"Save this to a file named <filename>src/main/java/org/hibernate/tutorial/"
"domain/Person.java</filename>"
msgstr ""
"Guarde esto en un archivo llamado <filename>src/main/java/org/hibernate/"
"tutorial/domain/Person.java</filename>"

#. Tag: para
#: tutorial.xml:653
#, no-c-format
msgid ""
"Next, create the new mapping file as <filename>src/main/resources/org/"
"hibernate/tutorial/domain/Person.hbm.xml</filename>"
msgstr ""
"Luego, cree el nuevo archivo de mapeo como <filename>src/main/resources/org/"
"hibernate/tutorial/domain/Person.hbm.xml</filename>"

#. Tag: programlisting
#: tutorial.xml:658
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""

#. Tag: para
#: tutorial.xml:660
#, no-c-format
msgid "Finally, add the new mapping to Hibernate's configuration:"
msgstr "Finalmente, añada el nuevo mapeo a la configuración de Hibernate:"

#. Tag: programlisting
#: tutorial.xml:664
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""

#. Tag: para
#: tutorial.xml:666
#, no-c-format
msgid ""
"Create an association between these two entities. Persons can participate in "
"events, and events have participants. The design questions you have to deal "
"with are: directionality, multiplicity, and collection behavior."
msgstr ""
"Vamos a crear una asociación entre estas dos entidades. Las personas pueden "
"participar en los eventos y los eventos cuentan con participantes. Las "
"cuestiones de diseño con las que tenemos que tratar son: direccionalidad, "
"multiplicidad y comportamiento de la colección."

#. Tag: title
#: tutorial.xml:676
#, no-c-format
msgid "A unidirectional Set-based association"
msgstr "Una asociación unidireccional basada en Set"

#. Tag: para
#: tutorial.xml:678
#, no-c-format
msgid ""
"By adding a collection of events to the <literal>Person class, you "
"can easily navigate to the events for a particular person, without executing "
"an explicit query - by calling <literal>Person#getEvents. Multi-"
"valued associations are represented in Hibernate by one of the Java "
"Collection Framework contracts; here we choose a <interfacename>java.util."
"Set</interfacename> because the collection will not contain duplicate "
"elements and the ordering is not relevant to our examples:"
msgstr ""
"Al agregar una colección de eventos a la clase <literal>Person, "
"puede navegar fácilmente a los eventos de una persona en particular, sin "
"ejecutar una petición explícita - llamando a <literal>Person#getEvents ya que la colección no "
"contendrá elementos duplicados y el orden no es relevante para nuestros "
"ejemplos."

#. Tag: programlisting
#: tutorial.xml:689
#, no-c-format
msgid ""
"<![CDATA[public class Person {\n"
"\n"
"    private Set events = new HashSet();\n"
"\n"
"    public Set getEvents() {\n"
"        return events;\n"
"    }\n"
"\n"
"    public void setEvents(Set events) {\n"
"        this.events = events;\n"
"    }\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:691
#, no-c-format
msgid ""
"Before mapping this association, let's consider the other side. We could "
"just keep this unidirectional or create another collection on the "
"<literal>Event, if we wanted to be able to navigate it from both "
"directions. This is not necessary, from a functional perspective. You can "
"always execute an explicit query to retrieve the participants for a "
"particular event. This is a design choice left to you, but what is clear "
"from this discussion is the multiplicity of the association: \"many\" valued "
"on both sides is called a <emphasis>many-to-many association. "
"Hence, we use Hibernate's many-to-many mapping:"
msgstr ""
"Antes de mapear esta asociación, considere el otro lado. Podriamos mantener "
"esto unidireccional o podríamos crear otra colección en el <literal>Event. Por lo tanto, utilizamos un "
"mapeo muchos-a-muchos de Hibernate:"

#. Tag: programlisting
#: tutorial.xml:704
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""

#. Tag: para
#: tutorial.xml:706
#, no-c-format
msgid ""
"Hibernate supports a broad range of collection mappings, a <literal>setn:"
"m</emphasis> entity relationship, an association table is required. Each row "
"in this table represents a link between a person and an event. The table "
"name is decalred using the <literal>table attribute of the "
"<literal>set element. The identifier column name in the "
"association, for the person side, is defined with the <literal>key "
"element, the column name for the event's side with the <literal>columnmany-to-many. You also have to "
"tell Hibernate the class of the objects in your collection (the class on the "
"other side of the collection of references)."
msgstr ""
"Hibernate soporta un amplio rango de mapeos de colección, el más común "
"<literal>set. Para una asociación muchos-a-muchos o la relación de "
"entidad <emphasis>n:m, se necesita una tabla de asociación. Cada "
"fila en esta tabla representa un enlace entre una persona y un evento. El "
"nombre de esta tabla se declara con el atributo <literal>table del "
"elemento <literal>set. El nombre de la columna identificadora en "
"la asociación, del lado de la persona, se define con el elemento "
"<literal>key, el nombre de columna para el lado del evento se "
"define con el atributo <literal>column del many-to-many:"
msgstr ""
"Vamos a reunir a algunas personas y eventos en un nuevo método en "
"<literal>EventManager:"

#. Tag: programlisting
#: tutorial.xml:737
#, no-c-format
msgid ""
"<![CDATA[    private void addPersonToEvent(Long personId, Long eventId) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Person aPerson = (Person) session.load(Person.class, personId);\n"
"        Event anEvent = (Event) session.load(Event.class, eventId);\n"
"        aPerson.getEvents().add(anEvent);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:739
#, no-c-format
msgid ""
"After loading a <literal>Person and an Event, "
"simply modify the collection using the normal collection methods. There is "
"no explicit call to <literal>update() or save() state, that is, bound to a particular "
"Hibernate <interfacename>org.hibernate.Session, Hibernate "
"monitors any changes and executes SQL in a write-behind fashion. The process "
"of synchronizing the memory state with the database, usually only at the end "
"of a unit of work, is called <emphasis>flushing. In our code, the "
"unit of work ends with a commit, or rollback, of the database transaction."
msgstr ""
"Después de cargar una <literal>Person y un Event o "
"<literal>save(); Hibernate detecta automáticamente que se ha "
"modificado la colección y que se necesita actualizarla. Esto se denomina "
"<emphasis>chequeo automático de desactualizaciones y también "
"puede probarlo modificando el nombre o la propiedad de fecha de cualquiera "
"de sus objetos. Mientras se encuentran en estado <emphasis>persistenteorg.hibernate.Session. En nuestro "
"código la unidad de trabajo termina con guardar o deshacer los cambios de la "
"transacción de la base de datos."

#. Tag: para
#: tutorial.xml:758
#, no-c-format
msgid ""
"You can load person and event in different units of work. Or you can modify "
"an object outside of a <interfacename>org.hibernate.Session, "
"when it is not in persistent state (if it was persistent before, this state "
"is called <emphasis>detached). You can even modify a collection "
"when it is detached:"
msgstr ""
"Puede cargar una persona y un evento en diferentes unidades de trabajo. "
"También puede modificar un objeto fuera de una <interfacename>org.hibernate."
"Session</interfacename>, cuando no se encuentra en estado persistente (si "
"antes era persistente denominamos a este estado <emphasis>separado makes a detached object persistent "
"again by binding it to a new unit of work, so any modifications you made to "
"it while detached can be saved to the database. This includes any "
"modifications (additions/deletions) you made to a collection of that entity "
"object."
msgstr ""
"La llamada a <literal>update hace que un objeto separado sea "
"persistente de nuevo enlazándolo a una nueva unidad de trabajo, así que "
"cualquier modificación que le realizó mientras estaba separado se puede "
"guardar en la base de datos. Esto incluye cualquier modificación (adiciones "
"o eliminaciones) que le hizo a una colección de ese objeto entidad."

#. Tag: para
#: tutorial.xml:778
#, no-c-format
msgid ""
"This is not much use in our example, but it is an important concept you can "
"incorporate into your own application. Complete this exercise by adding a "
"new action to the main method of the <literal>EventManager and "
"call it from the command line. If you need the identifiers of a person and "
"an event - the <literal>save() method returns it (you might have "
"to modify some of the previous methods to return that identifier):"
msgstr ""
"Esto no se utiliza mucho en nuestro ejemplo, pero es un concepto importante "
"que puede incorporar en su propia aplicación. Complete este ejercicio "
"agregando una nueva acción al método main de <literal>EventManager "
"y llámela desde la línea de comandos. Si necesita los identificadores de una "
"persona y de un evento - el método <literal>save() los retorna "
"(pueda que necesite modificar algunos de los métodos anteriores para "
"retornar ese identificador):"

#. Tag: programlisting
#: tutorial.xml:786
#, no-c-format
msgid ""
"<![CDATA[        else if (args[0].equals(\"addpersontoevent\")) {\n"
"            Long eventId = mgr.createAndStoreEvent(\"My Event\", new Date"
"());\n"
"            Long personId = mgr.createAndStorePerson(\"Foo\", \"Bar\");\n"
"            mgr.addPersonToEvent(personId, eventId);\n"
"            System.out.println(\"Added person \" + personId + \" to event \" "
"+ eventId);\n"
"        }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:788
#, no-c-format
msgid ""
"This is an example of an association between two equally important classes : "
"two entities. As mentioned earlier, there are other classes and types in a "
"typical model, usually \"less important\". Some you have already seen, like "
"an <literal>int or a java.lang.String. We "
"call these classes <emphasis>value types, and their instances "
"<emphasis>depend on a particular entity. Instances of these types "
"do not have their own identity, nor are they shared between entities. Two "
"persons do not reference the same <literal>firstname object, even "
"if they have the same first name. Value types cannot only be found in the "
"JDK , but you can also write dependent classes yourself such as an "
"<literal>Address or MonetaryAmount class. In "
"fact, in a Hibernate application all JDK classes are considered value types."
msgstr ""
"Esto fue un ejemplo de una asociación entre dos clases igualmente "
"importantes: dos entidades. Como se mencionó anteriormente, hay otras clases "
"y tipos en un modelo típico, usualmente \"menos importantes\". Algunos de "
"ustedes las habrán visto, como un <literal>int o un "
"<classname>java.lang.String. Denominamos a estas clases "
"<emphasis>tipos de valor y sus instancias dependen, incluso si "
"tienen el mismo nombre. Los tipos de valor no sólo pueden encontrarse en el "
"JDK, sino que también puede escribir por sí mismo clases dependientes como "
"por ejemplo, <literal>Address o MonetaryAmount. "
"De hecho, en una aplicación Hibernate todas las clases JDK se consideran "
"como tipos de valor. "

#. Tag: para
#: tutorial.xml:806
#, no-c-format
msgid ""
"You can also design a collection of value types. This is conceptually "
"different from a collection of references to other entities, but looks "
"almost the same in Java."
msgstr ""
"También puede diseñar una colección de tipos de valor. Esto es "
"conceptualmente diferente de una colección de referencias a otras entidades, "
"pero se ve casi igual en Java."

#. Tag: title
#: tutorial.xml:815
#, no-c-format
msgid "Collection of values"
msgstr "Colección de valores"

#. Tag: para
#: tutorial.xml:817
#, no-c-format
msgid ""
"Let's add a collection of email addresses to the <literal>Person "
"entity. This will be represented as a <interfacename>java.util.Setjava.lang.String instances:"
msgstr ""
"Vamos a agregar una colección de direcciones de correo electrónico a la "
"entidad <literal>Person. Esto se representará como un "
"<interfacename>java.util.Set de las instnaicas "
"<classname>java.lang.String:"

#. Tag: programlisting
#: tutorial.xml:823
#, no-c-format
msgid ""
"<![CDATA[    private Set emailAddresses = new HashSet();\n"
"\n"
"    public Set getEmailAddresses() {\n"
"        return emailAddresses;\n"
"    }\n"
"\n"
"    public void setEmailAddresses(Set emailAddresses) {\n"
"        this.emailAddresses = emailAddresses;\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:825
#, no-c-format
msgid "The mapping of this <literal>Set is as follows:"
msgstr "El mapeo de este <literal>Set es así:"

#. Tag: programlisting
#: tutorial.xml:829
#, no-c-format
msgid ""
"<![CDATA[        "
msgstr ""

#. Tag: para
#: tutorial.xml:831
#, no-c-format
msgid ""
"The difference compared with the earlier mapping is the use of the "
"<literal>element part which tells Hibernate that the collection "
"does not contain references to another entity, but is rather a collection "
"whose elements are values types, here specifically of type <literal>string attribute of the set element defines the foreign-key column name in the "
"collection table. The <literal>column attribute in the "
"<literal>element element defines the column name where the email "
"address values will actually be stored."
msgstr ""
"La diferencia comparado con el mapeo anterior es el uso de la parte "
"<literal>element, que le dice a Hibernate que la colección no "
"contiene referencias a otra entidad, sino que es una colección de elementos "
"que son tipos de valores, aquí especificamente de tipo <literal>String del elemento "
"<literal>set determina el nombre de la tabla para la colección. El "
"elemento <literal>key define el nombre de la columna clave foránea "
"en la tabla de colección. El atributo <literal>column en el "
"elemento <literal>element define el nombre de la columna donde "
"realmente se almacenarán los valores de la dirección de correo electrónico."

#. Tag: para
#: tutorial.xml:847
#, no-c-format
msgid "Here is the updated schema:"
msgstr "Este es el esquema actualizado:"

#. Tag: programlisting
#: tutorial.xml:851
#, no-c-format
msgid ""
"<![CDATA[\n"
"  _____________        __________________\n"
" |             |      |                  |       _____________\n"
" |   EVENTS    |      |   PERSON_EVENT   |      |             |       "
"___________________\n"
" |_____________|      |__________________|      |    PERSON   |      "
"|                   |\n"
" |             |      |                  |      |_____________|      | "
"PERSON_EMAIL_ADDR |\n"
" | *EVENT_ID   | <--> | *EVENT_ID        |      |             |      |"
"___________________|\n"
" |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  | <--> |  "
"*PERSON_ID       |\n"
" |  TITLE      |      |__________________|      |  AGE        |      |  "
"*EMAIL_ADDR      |\n"
" |_____________|                                |  FIRSTNAME  |      |"
"___________________|\n"
"                                                |  LASTNAME   |\n"
"                                                |_____________|\n"
" ]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:853
#, no-c-format
msgid ""
"You can see that the primary key of the collection table is in fact a "
"composite key that uses both columns. This also implies that there cannot be "
"duplicate email addresses per person, which is exactly the semantics we need "
"for a set in Java."
msgstr ""
"Puede ver que la clave principal de la tabla de colección es, de hecho, una "
"clave compuesta que utiliza ambas columnas. Esto también implica que no "
"pueden haber direcciones de correo electrónico duplicadas por persona, la "
"cual es exactamente la semántica que necesitamos para un conjunto en Java."

#. Tag: para
#: tutorial.xml:859
#, no-c-format
msgid ""
"You can now try to add elements to this collection, just like we did before "
"by linking persons and events. It is the same code in Java:"
msgstr ""
"Ahora, puede tratar de agregar elementos a esta colección, al igual que lo "
"hicimos antes vinculando personas y eventos. Es el mismo código en Java."

#. Tag: programlisting
#: tutorial.xml:864
#, no-c-format
msgid ""
"<![CDATA[    private void addEmailToPerson(Long personId, String "
"emailAddress) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Person aPerson = (Person) session.load(Person.class, personId);\n"
"        // adding to the emailAddress collection might trigger a lazy load "
"of the collection\n"
"        aPerson.getEmailAddresses().add(emailAddress);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:866
#, no-c-format
msgid ""
"This time we did not use a <emphasis>fetch query to initialize "
"the collection. Monitor the SQL log and try to optimize this with an eager "
"fetch."
msgstr ""
"Esta vez no utilizamos una petición de <emphasis>búqueda - fetch - "
"class:"
msgstr ""
"Primero, agregue una colección de participantes a la clase <literal>Event."
msgstr ""
"Ahora mapee este lado de la asociación en <literal>Event.hbm.xml."

#. Tag: programlisting
#: tutorial.xml:904
#, no-c-format
msgid ""
"<![CDATA[        "
msgstr ""

#. Tag: para
#: tutorial.xml:906
#, no-c-format
msgid ""
"These are normal <literal>set mappings in both mapping documents. "
"Notice that the column names in <literal>key and many-to-"
"many</literal> swap in both mapping documents. The most important addition "
"here is the <literal>inverse=\"true\" attribute in the "
"<literal>set element of the Event's collection "
"mapping."
msgstr ""
"Estos son mapeos normales de <literal>set en ambos documentos de "
"mapeo. Note que los nombres de las columnas en <literal>key y "
"<literal>many-to-many se intercambiaron en ambos documentos de "
"mapeo. La adición más importante aquí es el atributo <literal>inverse=\"true"
"\"</literal> en el elemento set del mapeo de colección de "
"<literal>Event."

#. Tag: para
#: tutorial.xml:914
#, no-c-format
msgid ""
"What this means is that Hibernate should take the other side, the "
"<literal>Person class, when it needs to find out information about "
"the link between the two. This will be a lot easier to understand once you "
"see how the bi-directional link between our two entities is created."
msgstr ""
"Esto significa que Hibernate debe tomar el otro lado, la clase "
"<literal>Person, cuando necesite encontrar información sobre el "
"enlace entre las dos. Esto será mucho más fácil de entender una vez que vea "
"como se crea el enlace bidireccional entre nuestras dos entidades."

#. Tag: title
#: tutorial.xml:923
#, no-c-format
msgid "Working bi-directional links"
msgstr "Trabajo con enlaces bidireccionales"

#. Tag: para
#: tutorial.xml:925
#, no-c-format
msgid ""
"First, keep in mind that Hibernate does not affect normal Java semantics. "
"How did we create a link between a <literal>Person and an "
"<literal>Event in the unidirectional example? You add an instance "
"of <literal>Event to the collection of event references, of an "
"instance of <literal>Person. If you want to make this link bi-"
"directional, you have to do the same on the other side by adding a "
"<literal>Person reference to the collection in an Event y un Event a la colección de referencias de eventos de una "
"instancia de <literal>Person. Si quiere que este enlace funcione "
"bidireccionalmente, tiene que hacer lo mismo del otro lado, añadiendo una "
"referencia <literal>Person a la colección en un Event):"
msgstr ""
"Muchos desarrolladores programan a la defensiva y crean métodos de "
"administración de enlaces para establecer correctamente ambos lados, (por "
"ejemplo, en <literal>Person):"

#. Tag: programlisting
#: tutorial.xml:940
#, no-c-format
msgid ""
"<![CDATA[    protected Set getEvents() {\n"
"        return events;\n"
"    }\n"
"\n"
"    protected void setEvents(Set events) {\n"
"        this.events = events;\n"
"    }\n"
"\n"
"    public void addToEvent(Event event) {\n"
"        this.getEvents().add(event);\n"
"        event.getParticipants().add(this);\n"
"    }\n"
"\n"
"    public void removeFromEvent(Event event) {\n"
"        this.getEvents().remove(event);\n"
"        event.getParticipants().remove(this);\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:942
#, no-c-format
msgid ""
"The get and set methods for the collection are now protected. This allows "
"classes in the same package and subclasses to still access the methods, but "
"prevents everybody else from altering the collections directly. Repeat the "
"steps for the collection on the other side."
msgstr ""
"Los métodos get y set para la colección ahora se encuentran protegidos. Esto "
"le permite a las clases en el mismo paquete y a las subclases acceder aún a "
"los métodos, pero impide a cualquier otro que desordene las colecciones "
"directamente. Repita los pasos para la colección del otro lado."

#. Tag: para
#: tutorial.xml:949
#, no-c-format
msgid ""
"What about the <literal>inverse mapping attribute? For you, and "
"for Java, a bi-directional link is simply a matter of setting the references "
"on both sides correctly. Hibernate, however, does not have enough "
"information to correctly arrange SQL <literal>INSERT and "
"<literal>UPDATE statements (to avoid constraint violations). "
"Making one side of the association <literal>inverse tells "
"Hibernate to consider it a <emphasis>mirror of the other side. "
"That is all that is necessary for Hibernate to resolve any issues that arise "
"when transforming a directional navigation model to a SQL database schema. "
"The rules are straightforward: all bi-directional associations need one side "
"as <literal>inverse. In a one-to-many association it has to be the "
"many-side, and in many-to-many association you can select either side."
msgstr ""
"¿Y el atributo de mapeo <literal>inverse? Para usted y para Java, "
"un enlace bidireccional es simplemente cuestión de establecer correctamente "
"las referencias en ambos lados. Sin embargo, Hibernate no tiene suficiente "
"información para organizar correctamente declaraciones <literal>INSERTUPDATE de SQL (para evitar violaciones de "
"restricciones). El hacer un lado de la asociación <literal>inverse "
"le dice a Hibernate que lo considere un <emphasis>espejo del otro "
"lado. Eso es todo lo necesario para que Hibernate resuelva todos los asuntos "
"que surgen al transformar un modelo de navegación direccional a un esquema "
"de base de datos SQL. Las reglas son muy simples: todas las asociaciones "
"bidireccionales necesitan que uno de los lados sea <literal>inverse and "
"<literal>Transaction almost like a standalone application. "
"However, some common patterns are useful. You can now write an "
"<literal>EventManagerServlet. This servlet can list all events "
"stored in the database, and it provides an HTML form to enter new events."
msgstr ""
"Una aplicación web de Hibernate utiliza <literal>Session y "
"<literal>Transaction casi como una aplicación autónoma. Sin "
"embargo, algunos patrones comunes son útiles. Ahora puede escribir un "
"<literal>EventManagerServlet. Este servlet puede enumerar todos "
"los eventos almacenados en la base de datos y proporciona una forma HTML "
"para ingresar eventos nuevos."

#. Tag: title
#: tutorial.xml:975
#, no-c-format
msgid "Writing the basic servlet"
msgstr "Escritura de un servlet básico"

#. Tag: para
#: tutorial.xml:977
#, no-c-format
msgid ""
"First we need create our basic processing servlet. Since our servlet only "
"handles HTTP <literal>GET requests, we will only implement the "
"<literal>doGet() method:"
msgstr ""
"Primero necesitamos crear nuestro servlet de procesamiento básico. Ya que "
"nuestro servlet solo maneja pedidos <literal>GET HTTP sólamente, "
"solo implementaremos el método <literal>doGet():"

#. Tag: programlisting
#: tutorial.xml:983
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.web;\n"
"\n"
"// Imports\n"
"\n"
"public class EventManagerServlet extends HttpServlet {\n"
"\n"
"    protected void doGet(\n"
"            HttpServletRequest request,\n"
"            HttpServletResponse response) throws ServletException, "
"IOException {\n"
"\n"
"        SimpleDateFormat dateFormatter = new SimpleDateFormat( \"dd.MM.yyyy"
"\" );\n"
"\n"
"        try {\n"
"            // Begin unit of work\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"beginTransaction();\n"
"\n"
"            // Process request and render page...\n"
"\n"
"            // End unit of work\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"getTransaction().commit();\n"
"        }\n"
"        catch (Exception ex) {\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"getTransaction().rollback();\n"
"            if ( ServletException.class.isInstance( ex ) ) {\n"
"                throw ( ServletException ) ex;\n"
"            }\n"
"            else {\n"
"                throw new ServletException( ex );\n"
"            }\n"
"        }\n"
"    }\n"
"\n"
"}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:985
#, no-c-format
msgid ""
"Save this servlet as <filename>src/main/java/org/hibernate/tutorial/web/"
"EventManagerServlet.java</filename>"
msgstr ""
"Guarde este servlet como <filename>src/main/java/org/hibernate/tutorial/web/"
"EventManagerServlet.java</filename>"

#. Tag: para
#: tutorial.xml:990
#, no-c-format
msgid ""
"The pattern applied here is called <emphasis>session-per-request. "
"When a request hits the servlet, a new Hibernate <literal>Session "
"is opened through the first call to <literal>getCurrentSession() "
"on the <literal>SessionFactory. A database transaction is then "
"started. All data access occurs inside a transaction irrespective of whether "
"the data is read or written. Do not use the auto-commit mode in applications."
msgstr ""
"El patrón aplicado aquí se llama <emphasis>sesión-por-petición. "
"Cuando una petición llega al servlet, se abre una nueva <literal>Session en el SessionFactory use a new Hibernate Session "
"for every database operation. Use one Hibernate <literal>Session "
"that is scoped to the whole request. Use <literal>getCurrentSession() utilice una nueva Session de "
"Hibernate para cada operación de base de datos. Utilice una "
"<literal>Session Hibernate que cubra el campo de todo el pedido. "
"Utilice <literal>getCurrentSession() para vincularlo "
"automáticamente al hilo de Java actual."

#. Tag: para
#: tutorial.xml:1006
#, no-c-format
msgid ""
"Next, the possible actions of the request are processed and the response "
"HTML is rendered. We will get to that part soon."
msgstr ""
"Después, se procesan las acciones posibles del pedido y se entrega la "
"respuesta HTML. Llegaremos a esa parte muy pronto. "

#. Tag: para
#: tutorial.xml:1011
#, no-c-format
msgid ""
"Finally, the unit of work ends when processing and rendering are complete. "
"If any problems occurred during processing or rendering, an exception will "
"be thrown and the database transaction rolled back. This completes the "
"<literal>session-per-request pattern. Instead of the transaction "
"demarcation code in every servlet, you could also write a servlet filter. "
"See the Hibernate website and Wiki for more information about this pattern "
"called <emphasis>Open Session in View. You will need it as soon "
"as you consider rendering your view in JSP, not in a servlet."
msgstr ""
"Finalmente, la unidad de trabajo termina cuando se completa el procesamiento "
"y la entrega. Si surgió algún problema durante el procesamiento o la "
"entrega , se presentará una excepción y la transacción de la base de datos "
"se deshará. Esto completa el patrón <literal>session-per-request. "
"En vez del código de demarcación de la transacción en todo servlet, también "
"podría escribir un filtro de servlet. Véa el sitio web de Hibernate y el "
"Wiki para obtener más información sobre este patrón llamado <emphasis>sesión "
"abierta en vista</emphasis>. Lo necesitará tan pronto como considere "
"representar su vista en JSP, no en un servlet."

#. Tag: title
#: tutorial.xml:1025
#, no-c-format
msgid "Processing and rendering"
msgstr "Procesamiento y entrega"

#. Tag: para
#: tutorial.xml:1027
#, no-c-format
msgid ""
"Now you can implement the processing of the request and the rendering of the "
"page."
msgstr ""
"Ahora puede implementar el procesamiento del pedido y la representación de "
"la página."

#. Tag: programlisting
#: tutorial.xml:1031
#, no-c-format
msgid ""
"<![CDATA[        // Write HTML header\n"
"        PrintWriter out = response.getWriter();\n"
"        out.println(\"<html>Event Manager"
"\");\n"
"\n"
"        // Handle actions\n"
"        if ( \"store\".equals(request.getParameter(\"action\")) ) {\n"
"\n"
"            String eventTitle = request.getParameter(\"eventTitle\");\n"
"            String eventDate = request.getParameter(\"eventDate\");\n"
"\n"
"            if ( \"\".equals(eventTitle) || \"\".equals(eventDate) ) {\n"
"                out.println(\"<b>Please enter event title and date.Added event.\");\n"
"            }\n"
"        }\n"
"\n"
"        // Print page\n"
"       printEventForm(out);\n"
"       listEvents(out, dateFormatter);\n"
"\n"
"       // Write HTML footer\n"
"       out.println(\"</body>\");\n"
"       out.flush();\n"
"       out.close();]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:1033
#, no-c-format
msgid ""
"This coding style, with a mix of Java and HTML, would not scale in a more "
"complex application—keep in mind that we are only illustrating basic "
"Hibernate concepts in this tutorial. The code prints an HTML header and a "
"footer. Inside this page, an HTML form for event entry and a list of all "
"events in the database are printed. The first method is trivial and only "
"outputs HTML:"
msgstr ""
"Dado que este estilo de codificación con una mezcla de Java y HTML no "
"escalaría en una aplicación más compleja - tenga en cuenta que sólo estamos "
"ilustrando los conceptos básicos de Hibernate en este tutorial. El código "
"imprime una cabecera y un pie de página HTML. Dentro de esta página se "
"imprime una forma HTML para entrada de eventos y se imprime una lista de "
"todos los eventos en la base de datos. El primer método es trivial y su "
"salida se realiza únicamente en HTML:"

#. Tag: programlisting
#: tutorial.xml:1042
#, no-c-format
msgid ""
"<![CDATA[    private void printEventForm(PrintWriter out) {\n"
"        out.println(\"<h2>Add new event:\");\n"
"        out.println(\"<form>\");\n"
"        out.println(\"Title: <input name='eventTitle' length='50'/>
" "\");\n" " out.println(\"Date (e.g. 24.12.2009): <input name='eventDate' " "length='10'/><br/>\");\n" " out.println(\"<input type='submit' name='action' value='store'/>" "\");\n" " out.println(\"</form>\");\n" " }]]>" msgstr "" #. Tag: para #: tutorial.xml:1044 #, no-c-format msgid "" "The <literal>listEvents() method uses the Hibernate " "<literal>Session bound to the current thread to execute a query:" msgstr "" "El método <literal>listEvents() utiliza Hibernate " "<literal>Session vinculado al hilo actual para ejecutar una " "petición:" #. Tag: programlisting #: tutorial.xml:1050 #, no-c-format msgid "" "<![CDATA[ private void listEvents(PrintWriter out, SimpleDateFormat " "dateFormatter) {\n" "\n" " List result = HibernateUtil.getSessionFactory()\n" " .getCurrentSession().createCriteria(Event.class).list();\n" " if (result.size() > 0) {\n" " out.println(\"<h2>Events in database:\");\n" " out.println(\"<table border='1'>\");\n" " out.println(\"<tr>\");\n" " out.println(\"<th>Event title\");\n" " out.println(\"<th>Event date\");\n" " out.println(\"</tr>\");\n" " Iterator it = result.iterator();\n" " while (it.hasNext()) {\n" " Event event = (Event) it.next();\n" " out.println(\"<tr>\");\n" " out.println(\"<td>\" + event.getTitle() + \"
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.