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, a ação <literal>store, é despachada ao método " "<literal>createAndStoreEvent(), que também utiliza a " "<literal>Session da thread atual:" #. 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 "" "O servlet está completo agora. Uma solicitação ao servlet será processada " "com uma única <literal>Session e Transaction. " "Quanto antes estiver no aplicativo autônomo, maior a chance do Hibernate " "vincular automaticamente estes objetos à thread atual de execução. Isto lhe " "dá a liberdade para inserir seu código e acessar a <literal>SessionFactory\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 e implementar, chame seu diretório de projeto <literal>ant " "war</literal> e copie o arquivo hibernate-tutorial.war " "para seu diretório Tomcat <literal>webapp. " #. 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 "" "Caso você não possua o Tomcat instalado, baixe isto do <ulink url=\"http://" "tomcat.apache.org/\" /> e siga as instruções de instalação. Nosso aplicativo " "não solicita alterações à configuração Tomcat padrão. " #. 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 "" "Uma vez implementado e com o Tomcat rodando, acesse o aplicativo em " "<literal>http://localhost:8080/hibernate-tutorial/eventmanager. " "Tenha a certeza de observar o log do Tomcat para ver o Hibernate inicializar " "quando a primeira solicitação chegar em seu servlet (o inicializador " "estático no <literal>HibernateUtil é chamado) e para obter o " "resultado detalhado caso exceções aconteçam. " #. Tag: title #: tutorial.xml:1112 #, no-c-format msgid "Summary" msgstr "Sumário" #. 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 cobriu itens básicos de como escrever um aplicativo Hibernate " "autônomo simples e um aplicativo da web pequeno. A partir do Hibernate " "<ulink url=\"http://hibernate.org\">website você poderá encontrar " "mais tutoriais disponíveis."

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

a, cdata, hibernate, hibernate, java, maven, o, o, sql, tag, tag, the, the, this

The Hibernate tutorial.po source code

# translation of tutorial.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# translation of Collection_Mapping.po to
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2006.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# , 2007.
# Michael H. Smith <mhideo@redhat.com>, 2007.
# Glaucia Cintra <gcintra@redhat.com>, 2007.
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-19 14:09+1000\n"
"Last-Translator: \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 ""
"Intencionado para novos usuários, este capítulo fornece uma introdução "
"detalhada do Hibernate, começando com um aplicativo simples usando um banco "
"de dados em memória. O tutorial é baseado num tutorial anterior desenvolvido "
"por Michael Gloegl. Todo o código está contido no diretório "
"<filename>tutorials/web da fonte do projeto."

#. 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 espera que o usuário tenha conhecimento de ambos Java e SQL. "
"Caso você tenha um conhecimento limitado do JAVA ou SQL, é recomendado que "
"você inicie com uma boa introdução àquela tecnologia, antes de tentar "
"entender o 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 ""
"Esta distribuição contém outro aplicativo de amostra sob o diretório de "
"fonte do projeto <filename>tutorial/eg."

#. Tag: title
#: tutorial.xml:62
#, no-c-format
msgid "Part 1 - The first Hibernate Application"
msgstr "Parte 1 – A primeira aplicação 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 ""
"Vamos supor que precisemos de uma aplicação com um banco de dados pequeno "
"que possa armazenar e atender os eventos que queremos, além das informações "
"sobre os hosts destes 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 ""
"Mesmo que usando qualquer banco de dados do qual você se sinta confortável, "
"nós usaremos <ulink url=\"http://hsqldb.org/\">HSQLDB (o em memória, "
"banco de dados Java) para evitar a descrição de instalação/configuração de "
"quaisquer servidores do banco de dados."

#. Tag: title
#: tutorial.xml:79
#, no-c-format
msgid "Setup"
msgstr "Configuração"

#. 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 ""
"O primeiro passo em que precisamos tomar é configurar o ambiente de "
"desenvolvimento. Nós usaremos o \"layout padrão\" suportado por muitas "
"ferramentas de construção, tais como <ulink url=\"http://maven.org\">Maven. Assim como este tutorial "
"deve ser um aplicativo da web, nós criaremos e faremos uso dos diretórios "
"<filename>src/main/java, src/main/resources "
"e <filename>src/main/webapp."

#. 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 ""
"Nós usaremos Maven neste tutorial, tirando vantagem destas capacidades de "
"dependência transitiva assim como a habilidade de muitos IDEs de configurar "
"automaticamente um projeto baseado no descritor 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 ""
"O uso do Maven não é obrigatório. Caso você deseje usar outra tecnologia "
"para construir este tutorial (tal como Ant), o layout continuará o mesmo. A "
"única mudança é que você precisará contar manualmente para todas as "
"dependências necessárias. Caso você utilize <ulink url=\"http://ant.apache."
"org/ivy/\">Ivy</ulink> para fornecer um gerenciamento de dependência "
"transitiva, você continuará a usar as dependências mencionadas abaixo. Do "
"contrário, você precisará encontrar <emphasis>todas as "
"dependências, ambas explícitas e transitivas, além de adicioná-las às "
"classpath de projetos. Caso trabalhando da vinculação de distribuição "
"Hibernate, quer dizer <filename>hibernate3.jar, todos os "
"artefatos no diretório <filename>lib/required e todos os arquivos "
"a partir do diretório <filename>lib/bytecode/cglib ou "
"<filename>lib/bytecode/javassist. Adicionalmente, você precisará "
"de ambos servlet-api jar e um dos slf4j logging backends. "

#. Tag: para
#: tutorial.xml:117
#, no-c-format
msgid ""
"Save this file as <filename>pom.xml in the project root directory."
msgstr ""
"Salve este arquivo como <filename>pom.xml no diretório raiz do "
"projeto."

#. Tag: title
#: tutorial.xml:124
#, no-c-format
msgid "The first class"
msgstr "A primeira Classe"

#. 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 ""
"Agora, iremos criar uma classe que representa o evento que queremos "
"armazenar na base de dados. Isto é uma classe JavaBean simples com algumas "
"propriedades:"

#. 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 ""
"Você pode ver que esta classe usa o padrão JavaBean para o nome convencional "
"dos métodos de propriedade getter e setter, como também a visibilidade "
"privada dos campos. Este é um padrão de projeto recomendado, mas não "
"requerido. O Hibernate pode também acessar campos diretamente, o benefício "
"para os métodos de acesso é a robustez para o refactoring. "

#. 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 ""
"A propriedade <literal>id mantém um único valor de identificação "
"para um evento particular. Todas as classes persistentes da entidade (bem "
"como aquelas classes dependentes de menos importância) precisam de uma "
"propriedade de identificação, caso nós queiramos usar o conjunto completo de "
"características do Hibernate. De fato, a maioria das aplicações, "
"especialmente. aplicações web, precisam distinguir os objetos pelo "
"identificador. Portanto, você deverá considerar esta, uma característica ao "
"invés de uma limitação. Porém, nós normalmente não manipulamos a identidade "
"de um objeto, conseqüentemente o método setter deverá ser privado. O "
"Hibernate somente nomeará os identificadores quando um objeto for salvo. O "
"Hibernate pode acessar métodos públicos, privados, e protegidos, como também "
"campos públicos, privados, protegidos diretamente. A escolha é sua e você "
"pode adaptar seu projeto de aplicação."

#. 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 ""
"O construtor sem argumentos é um requerimento para todas as classes "
"persistentes; O Hibernate precisa criar para você os objetos usando Java "
"Reflection. O construtor pode ser privado, porém, a visibilidade do pacote é "
"requerida para a procuração da geração em tempo de execução e recuperação "
"eficiente dos dados sem a instrumentação de bytecode."

#. 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 ""
"Note que o Hibernate DTD é muito sofisticado. Você pode usar isso para auto-"
"conclusão no mapeamento XML dos elementos e funções no seu editor ou IDE. "
"Você também pode abrir o arquivo DTD no seu editor. Esta é a maneira mais "
"fácil de ter uma visão geral de todos os elementos e funções e dos padrões, "
"como também alguns comentários. Note que o Hibernate não irá carregar o "
"arquivo DTD da web, e sim da classpath da aplicação. O arquivo DTD está "
"incluído no <filename>hibernate-core.jar (como também no "
"<filename>hibernate3.jar, caso usando a vinculação de "
"distribuição."

#. 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 ""
"Nós omitiremos a declaração do DTD nos exemplos futuros para encurtar o "
"código. Isto, é claro, não é 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 as duas tags <literal>hibernate-mapping, inclua um elemento "
"<literal>class. Todas as classes persistentes da entidade "
"(novamente, poderá haver mais tarde, dependências sobre as classes que não "
"são classes-primárias de entidades) necessitam do tal mapeamento, para uma "
"tabela na base de dados 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 ""
"Até agora, informamos o Hibernate sobre como fazer para persistir e carregar "
"objetos da classe <literal>Event da tabela EVENTS"
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 é a declaração de uma propriedade do "
"identificador. O atributo do mapeamento <literal>name=\"id\" "
"declara que o nome da propriedade JavaBeans e informa o Hibernate a utilizar "
"os métodos <literal>getId() and setId() para "
"acessar a propriedade. A atributo da coluna informa o Hibernate qual coluna "
"da tabela <literal>EVENTS mantém o valor de chave primária."

#. 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 ""
"O elemento <literal>generator aninhado especifica a estratégia da "
"geração do identificador (como os valores do identificador são gerados?). "
"Neste caso, nós escolhemos <literal>native, do qual oferece um "
"nível de portabilidade dependendo no dialeto do banco de dados configurado. "
"O Hibernate suporta o banco de dados gerado, globalmente único, assim como a "
"aplicação determinada, identificadores. A geração do valor do identificador "
"é também um dos muitos pontos de extensão do Hibernate e você pode realizar "
"o plugin na sua própria estratégia."

#. Tag: para
#: tutorial.xml:249
#, fuzzy, no-c-format
msgid ""
"<literal>native is no longer consider the best strategy in terms "
"of portability. for further discussion, see"
msgstr ""
"<literal>native não é mais considerada a melhor estratégia em "
"termos de portabilidade. Para maiores informações, 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 ""
"Finalmente, incluiremos as declarações para as propriedades persistentes da "
"classe no arquivo mapeado. Por padrão, nenhuma das propriedades da classe é "
"considerada 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 ""
"Assim como com o elemento <literal>id, a função nameproperty informa ao Hibernate qual "
"método getter e setter deverá usar. Assim, neste caso, o Hibernate irá "
"procurar pelos métodos <literal>getDate(), setDate()getTitle() e 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 ""
"Porque fazer o mapeamento da propriedade <literal>date incluído na "
"função <literal>column, e no title não fazer? "
"Sem a função <literal>column o Hibernate, por padrão, utiliza o "
"nome da propriedade como o nome da coluna. Isto funciona bem para o "
"<literal>title. Entretanto, o date é uma "
"palavra-chave reservada na maioria dos bancos de dados, por isso seria "
"melhor mapeá-lo com um nome 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 ""
"O mapeamento do <literal>title também não possui a função "
"<literal>type. O tipo que declaramos e utilizamos nos arquivos "
"mapeados, não são como você esperava, ou seja, funções de dados Java. Eles "
"também não são como os tipos de base de dados SQL. Esses tipos podem ser "
"chamados de <emphasis>Tipos de mapeamento Hibernate, que são "
"conversores que podem traduzir tipos de dados do Java para os tipos de dados "
"SQL e vice-versa. Novamente, o Hibernate irá tentar determinar a conversão "
"correta e mapeará o <literal>type próprio, caso o tipo da função "
"não estiver presente no mapeamento. Em alguns casos, esta detecção "
"automática (que usa Reflection sobre as classes Java) poderá não ter o "
"padrão que você espera ou necessita. Este é o caso com a propriedade "
"<literal>date. O Hibernate não sabe se a propriedade, que é do "
"<literal>java.util.Date, pode mapear para uma coluna do tipo "
"<literal>date do SQL, timestamp ou "
"<literal>time. Nós preservamos as informações sobre datas e horas "
"pelo mapeamento da propriedade com um conversor <literal>timestamp."

#. 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 ""
"O Hibernate realiza esta determinação de tipo de mapeamento usando a "
"reflexão quando os arquivos de mapeamentos são processados. Isto pode levar "
"tempo e recursos, portanto se você inicializar o desempenho, será importante "
"que você considere claramente a definição do tipo para uso."

#. 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 ""
"Salve este arquivo de mapeamento 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 "Configuração do 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 ""
"Nestas alturas, você deve possuir a classe persistente e seu arquivo de "
"mapeamento prontos. É o momento de configurar o Hibernate. Primeiro, vamos "
"configurar o HSQLDB para rodar no \"modo do servidor\"."

#. Tag: para
#: tutorial.xml:324
#, no-c-format
msgid "We do this do that the data remains between runs."
msgstr ""
"Nós realizamos isto para que aqueles dados permaneçam entre as execuções. "

#. 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 o HSQLBD novamente."

#. 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 ""
"O Hibernate conectará ao banco de dados no lugar de sua aplicação, portanto "
"ele precisará saber como obter as conexões. Para este tutorial nós usaremos "
"um pool de conexão autônomo (ao invés de <interfacename>javax.sql."
"DataSource</interfacename>). O Hibernate vem com o suporte para dois terços "
"dos pools de conexão JDBC de código aberto: <ulink url=\"https://sourceforge."
"net/projects/c3p0\">c3p0</ulink> e . No entanto, nós usaremos o pool de conexão interna "
"do 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 ""
"O pool de conexão interna do Hibernate não é recomendado para uso de "
"produção. Ele possui deficiência em diversos recursos encontrados em "
"qualquer pool de conexão apropriado."

#. 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, um arquivo mais sofisticado "
"<literal>hibernate.cfg.xml ou até mesmo uma instalação "
"programática completa. A maioria dos usuários prefere utilizar o arquivo de "
"configuração 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 "Perceba que este arquivo de configuração especifica um 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 a <literal>SessionFactory do Hibernate. A SessionFactory "
"é uma fábrica global responsável por uma base de dados particular. Se você "
"tiver diversas bases de dados, use diversas configurações <literal><"
"session-factory></literal>, geralmente em diversos arquivos de "
"configuração, para uma inicialização mais fácil. "

#. 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 contêm a "
"configuração necessária para a conexão JBDC. O elemento <literal>property "
"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 ""
"O gerenciamento automático de sessão do Hibernate para contextos de "
"persistência é bastante útil neste contexto. A opção <literal>hbm2ddl.auto na tarefa do Ant. Finalmente, "
"iremos adicionar os arquivos das classes de persistência mapeadas na "
"configuração."

#. 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 ""
"Salve este arquivo como <filename>hibernate.cfg.xml no diretório "
"<filename>src/main/resources."

#. Tag: title
#: tutorial.xml:406
#, no-c-format
msgid "Building with Maven"
msgstr "Construindo com o 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 ""
"Nós iremos construir agora o tutorial com Maven. Você necessitará que o "
"Maven esteja instalado; ele está disponível a partir do <ulink url=\"http://"
"maven.apache.org/download.html\">Maven download page</ulink>. O Maven "
"gravará o arquivo <filename>/pom.xml que criamos anteriormente, "
"além de saber como executar algumas tarefas do projeto básico. Primeiro, "
"vamos rodar o objetivo <literal>compile para nos certificarmos de "
"que tudo foi compilado até agora:"

#. 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 "Inicialização e Auxiliares "

#. 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 ""
"É hora de carregar e armazenar alguns objetos <literal>Event, mas "
"primeiro nós temos de completar a instalação com algum código de "
"infraestrutura. Você precisa inicializar o Hibernate pela construção de um "
"objeto <interfacename>org.hibernate.SessionFactory global e "
"o armazenamento dele em algum lugar de fácil acesso para o código da "
"aplicação. O <interfacename>org.hibernate.SessionFactory é "
"usado para obter instâncias <interfacename>org.hibernate.Sessionorg.hibernate.Session "
"representa uma unidade de single-threaded de trabalho. O <interfacename>org."
"hibernate.SessionFactory</interfacename> é um objeto global thread-safe, "
"instanciado uma 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 ""
"Criaremos uma classe de ajuda <literal>HibernateUtil, que cuida da "
"inicialização e faz acesso a uma <interfacename>org.hibernate."
"SessionFactory</interfacename> mais conveniente. "

#. 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 ""
"Salve 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 classe não só produz uma referência <interfacename>org.hibernate."
"SessionFactory</interfacename> global em seu inicializador estático, mas "
"também esconde o fato de que utiliza um autônomo estático. Nós poderemos "
"buscar pela referência <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 ""
"Se você der um nome à <literal>SessionFactory em seu arquivo de "
"configuração, o Hibernate irá, de fato, tentar vinculá-lo ao JNDI sob aquele "
"nome, depois que estiver construído. Outra opção melhor seria usar a "
"implementação JMX e deixar o recipiente JMX capaz, instanciar e vincular um "
"<literal>HibernateService ao JNDI. Essas opções avançadas são "
"discutidas no documento de referência do Hibernate. Tais opções avançadas "
"serão discutidas mais tarde."

#. 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 ""
"Você precisará agora configurar um sistema de logging. O Hibernate usa "
"logging comuns e lhe oferece a escolha entre o Log4j e o logging do JDK "
"1.4 . A maioria dos desenvolvedores prefere o Log4j: copie <literal>log4j."
"properties</literal> da distribuição do Hibernate no diretório etc/"
"</literal>, para seu diretório src, depois vá em "
"<literal>hibernate.cfg.xml. Dê uma olhada no exemplo de "
"configuração e mude as configurações se você quiser ter uma saída mais "
"detalhada. Por padrão, apenas as mensagens de inicialização do Hibernate são "
"mostradas no stdout."

#. 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 ""
"O tutorial de infra-estrutura está completo e nós já estamos preparados para "
"algum trabalho de verdade com o Hibernate. "

#. Tag: title
#: tutorial.xml:488
#, no-c-format
msgid "Loading and storing objects"
msgstr "Carregando e salvando 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() com um "
"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 ""
"Em <literal>createAndStoreEvent(), criamos um novo objeto de "
"<literal>Event, e passamos para o Hibernate. O Hibernate sabe como "
"tomar conta do SQL e executa <literal>INSERTs no banco de dados. "

#. 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 é designado a representar uma "
"unidade simples de trabalho (um pedaço atômico simples de trabalho a ser "
"executado). Nesta fase manteremos tudo muito simples e consideraremos uma "
"granularidade de um-para-um entre um <interface>org.hibernate.Session API. Neste caso em "
"particular, nós estamos usando as semânticas transacionais baseadas o JDBC, "
"mas isto pode rodar também com o 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 ""
"O que a <literal>sessionFactory.getCurrentSession() faz? Primeiro, "
"você pode chamar quantas vezes e de onde quiser, assim que você receber sua "
"<interfacename>org.hibernate.SessionFactory. O método "
"<literal>getCurrentSession() sempre retorna à unidade de trabalho "
"\"atual\". Você se lembra que nós mudamos a opção de configuração desse "
"mecanismo para \"thread\" em nosso <filename>src/main/resources/hibernate."
"cfg.xml</filename>? Devido a esta configuração, o contexto de uma unidade de "
"trabalho atual estará vinculada à thread Java atual que executa nossa "
"aplicação. "

#. Tag: para
#: tutorial.xml:532
#, no-c-format
msgid ""
"Hibernate offers three methods of current session tracking. The \"thread\" "
"based method is not intended for production use; it is merely useful for "
"prototyping and tutorials such as this one. Current session tracking is "
"discussed in more detail later on."
msgstr ""
"O Hibernate oferece três métodos da sessão atual. O método \"thread\" "
"baseado não possui por interesse o uso de produção; ele é basicamente útil "
"para prototyping e tutoriais tais como este. A sessão atual será discutida "
"em mais detalhes mais tarde."

#. Tag: para
#: tutorial.xml:541
#, no-c-format
msgid ""
"A <interface>org.hibernate.Session 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 ""
"Um <interface>org.hibernate.Session começa quando for "
"necessária, quando é feita a primeira chamada à <literal>getCurrentSession()"
"</literal>. É então limitada pelo Hibernate para a thread atual. Quando a "
"transação termina, tanto com commit quanto rollback, o Hibernate também "
"desvincula a <literal>Session da thread e fecha isso pra você. Se "
"você chamar <literal>getCurrentSession() novamente, você receberá "
"uma nova <literal>Session e poderá começar uma nova unidade de "
"trabalho. "

#. 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 ""
"Em relação ao escopo da unidade de trabalho, o Hibernate <interface>org."
"hibernate.Session</interface> deve ser utilizado para executar uma ou mais "
"operações do banco de dados? O exemplo acima utiliza uma <literal>Session para "
"aoperação de banco de dados <emphasis>every. Portanto, mesmo que "
"você o veja algumas vezes mais nos seguintes exemplos, considere "
"<emphasis>session-per-operation como um anti-modelo. Um "
"aplicativo  da web real será demonstrado mais adiante neste tutorial."

#. 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 ""
"Dê uma olhada no <xref linkend=\"transactions\"/> para mais informações a "
"respeito de manipulação de transação e demarcação. Nós também pulamos "
"qualquer manipulação de erro e rollback no exemplo anterior.  "

#. 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 rodar isto, nós faremos uso do Maven exec plugin para chamar nossa "
"classe com a instalação do classpath necessária: <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 "Você precisa executar o <command>mvn compile primeiramente."

#. 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 ""
"Você deverá ver, após a compilação, a inicialização do Hibernate e, "
"dependendo da sua configuração, muito log de saída. No final, você verá a "
"seguinte linha: "

#. 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 é o <literal>INSERT executado pelo Hibernate."

#. Tag: para
#: tutorial.xml:600
#, no-c-format
msgid "To list stored events an option is added to the main method:"
msgstr ""
"Adicionamos uma opção para o método principal com o objetivo de listar os "
"eventos arquivados: "

#. 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 ""
"Nos também adicionamos um novo <literal>listEvents() method is also added 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 ""
"Neste caso, nós usamos uma consulta Hibernate Query LanguageHQL (HQL), para "
"carregar todos os objetos <literal>Event existentes no banco de "
"dados. O Hibernate irá gerar o SQL apropriado, enviar para o banco de dados "
"e popular objetos <literal>Event com os dados. Você pode criar "
"consultas mais complexas com HQL. Consulte <xref linkend=\"queryhql\"/> para "
"maiores informações.  "

#. 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 ""
"Agora podemos chamar nossa nova funcionalidade usando, novamente, o Maven "
"exec plugin: <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 "Parte 2 - Mapeando associações "

#. 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 ""
"Nós mapeamos uma classe de entidade de persistência para uma tabela. Agora "
"vamos continuar e adicionar algumas associações de classe. Primeiro iremos "
"adicionar pessoas à nossa aplicação e armazenar os eventos em que elas "
"participam. "

#. Tag: title
#: tutorial.xml:640
#, no-c-format
msgid "Mapping the Person class"
msgstr "Mapeando a classe Person "

#. Tag: para
#: tutorial.xml:642
#, no-c-format
msgid "The first cut of the <literal>Person class looks like this:"
msgstr ""
"O primeira parte da classe <literal>Person parece-se com isto: "

#. 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 ""
"Salve isto ao arquivo nomeado <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 ""
"Após isto, crie um novo arquivo de mapeamento 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, adicione o novo mapeamento à configuração do 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 ""
"Crie agora uma associação entre estas duas entidades. As pessoas (Person) "
"podem participar de eventos, e eventos possuem participantes. As questões de "
"design com que teremos de lidar são: direcionalidade, multiplicidade e "
"comportamento de coleção. "

#. Tag: title
#: tutorial.xml:676
#, no-c-format
msgid "A unidirectional Set-based association"
msgstr "Uma associação unidirecional baseada em Configuração"

#. 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 ""
"Iremos adicionar uma coleção de eventos na classe <literal>Person. "
"Dessa forma, poderemos navegar pelos eventos de uma pessoa em particular, "
"sem executar uma consulta explicitamente, apenas chamando "
"<literal>Person#getEvents. As associações de valores múltiplos são "
"representadas no Hibernate por um dos contratos do Java Collection "
"Framework; aqui nós escolhemos um <interfacename>java.util.Set, 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 mapearmos esta associação, pense no outro lado. Claramente, "
"poderíamos apenas fazer isto de forma unidirecional. Ou poderíamos criar "
"outra coleção no <literal>Event, se quisermos navegar de ambas "
"direções. Isto não é necessário, de uma perspectiva funcional. Você poderá "
"sempre executar uma consulta explícita para recuperar os participantes de um "
"evento em particular. Esta é uma escolha de design que cabe a você, mas o "
"que é claro nessa discussão é a multiplicidade da associação: \"muitos\" "
"válidos em ambos os lados, nós chamamos isto de uma associação "
"<emphasis>muitos-para-muitos. Daqui pra frente, usaremos o "
"mapeamento muitos-para-muitos do 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 ""
"O Hibernate suporta todo tipo de mapeamento de coleção, sendo um "
"<literal>set mais comum. Para uma associação muitos-para-muitos ou "
"relacionamento de entidade <emphasis>n:m, é necessária uma tabela "
"de associação. Cada linha nessa tabela representa um link entre uma pessoa e "
"um evento. O nome da tabela é configurado com a função <literal>tableset. O nome da coluna identificadora "
"na associação, pelo lado da pessoa, é definido com o elemento <literal>key do many-to-many. Você também "
"precisa dizer para o Hibernate a classe dos objetos na sua coleção (a classe "
"do outro lado das coleções de referência)."

#. Tag: para
#: tutorial.xml:722
#, no-c-format
msgid "The database schema for this mapping is therefore:"
msgstr "O esquema de mapeamento para o banco de dados está a seguir: "

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

#. Tag: title
#: tutorial.xml:731
#, no-c-format
msgid "Working the association"
msgstr "Trabalhando a associação "

#. Tag: para
#: tutorial.xml:733
#, no-c-format
msgid ""
"Now we will bring some people and events together in a new method in "
"<literal>EventManager:"
msgstr ""
"Vamos reunir algumas pessoas e eventos em um novo método na classe "
"<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 ""
"Após carregar um <literal>Person e um Event, "
"simplesmente modifique a coleção usando os métodos normais de uma coleção. "
"Como você pode ver, não há chamada explícita para <literal>update()save(); o Hibernate detecta automaticamente "
"que a coleção foi modificada e que necessita ser atualizada. Isso é chamado "
"de <emphasis>checagem suja automática, e você também pode usá-la "
"modificando o nome ou a data de qualquer um dos seus objetos. Desde que eles "
"estejam no estado <emphasis>persistent, ou seja, limitado por uma "
"<literal>Session do Hibernate em particular, o Hibernate monitora "
"qualquer alteração e executa o SQL em modo de gravação temporária. O "
"processo de sincronização do estado da memória com o banco de dados, "
"geralmente apenas no final de uma unidade de trabalho, normalmente apenas no "
"final da unidade de trabalho, é chamado de <emphasis>flushing. No "
"nosso código, a unidade de trabalho termina com o commit , ou rollback, da "
"transação do banco de dados. "

#. 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 ""
"Você pode também querer carregar pessoas e eventos em diferentes unidades de "
"trabalho. Ou você modifica um objeto fora de um <interfacename>org.hibernate."
"Session</interfacename>, quando não se encontra no estado persistente (se já "
"esteve neste estado anteriormente, chamamos esse estado de "
"<emphasis>detached). Você pode até mesmo modificar uma coleção "
"quando esta se encontrar no estado detached:"

#. Tag: programlisting
#: tutorial.xml:767
#, 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\n"
"                .createQuery(\"select p from Person p left join fetch p."
"events where p.id = :pid\")\n"
"                .setParameter(\"pid\", personId)\n"
"                .uniqueResult(); // Eager fetch the collection so we can use "
"it detached\n"
"        Event anEvent = (Event) session.load(Event.class, eventId);\n"
"\n"
"        session.getTransaction().commit();\n"
"\n"
"        // End of first unit of work\n"
"\n"
"        aPerson.getEvents().add(anEvent); // aPerson (and its collection) is "
"detached\n"
"\n"
"        // Begin second unit of work\n"
"\n"
"        Session session2 = HibernateUtil.getSessionFactory()."
"getCurrentSession();\n"
"        session2.beginTransaction();\n"
"        session2.update(aPerson); // Reattachment of aPerson\n"
"\n"
"        session2.getTransaction().commit();\n"
"    }]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:769
#, no-c-format
msgid ""
"The call to <literal>update 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 ""
"A chamada <literal>update cria um objeto persistente novamente, "
"pode-se dizer que ele liga o objeto a uma nova unidade de trabalho, assim "
"qualquer modificação que você faça neste objeto enquanto estiver no estado "
"desanexado pode ser salvo no banco de dados. Isso inclui qualquer "
"modificação (adição/exclusão) que você faça em uma coleção da entidade deste "
"objeto.  "

#. 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 ""
"Bem, isso não é de grande utilidade na nossa situação atual, porém, é um "
"importante conceito que você pode criar em seu próprio aplicativo. No "
"momento, complete este exercício adicionando uma ação ao método principal da "
"classe <literal>EventManager e chame-o pela linha de comando. Se "
"você precisar dos identificadores de uma pessoa ou evento - o método "
"<literal>save() retornará estes identificadores (você poderá "
"modificar alguns dos métodos anteriores para retornar aquele 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 ""
"Este foi um exemplo de uma associação entre duas classes igualmente "
"importantes: duas entidades. Como mencionado anteriormente, há outras "
"classes e tipos dentro de um modelo típico, geralmente \"menos importante\". "
"Alguns você já viu, como um <literal>int ou uma Stringtipos de valoresdependem de uma entidade "
"particular. As instâncias desses tipos não possuem sua própria identidade, "
"nem são compartilhados entre entidades. Duas pessoas não referenciam o mesmo "
"objeto <literal>firstname mesmo se elas tiverem o mesmo objeto "
"firstname. Naturalmente, os tipos de valores não são apenas encontrados "
"dentro da JDK, mas você pode também criar suas classes como, por exemplo, "
"<literal>Address ou MonetaryAmount. De fato, no "
"aplicativo Hibernate todas as classes JDK são consideradas tipos de valores."

#. 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 ""
"Você também pode criar uma coleção de tipo de valores. Isso é "
"conceitualmente muito diferente de uma coleção de referências para outras "
"entidades, mas em Java parece ser quase a mesma coisa.  "

#. Tag: title
#: tutorial.xml:815
#, no-c-format
msgid "Collection of values"
msgstr "Coleção 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 adicionar uma coleção de endereços de e-mail à entidade "
"<literal>Person. Isto será representado como um "
"<interfacename>java.util.Set das instâncias java."
"lang.String</classname>:"

#. 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 "Segue abaixo o mapeamento deste <literal>Set: "

#. 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 ""
"A diferença comparada com o mapeamento anterior se encontra na parte "
"<literal>element, que informa ao Hibernate que a coleção não "
"contém referências à outra entidade, mas uma coleção de elementos do tipo "
"<literal>String. O nome da tag em minúsculo indica que se trata de "
"um tipo/conversor de mapeamento do Hibernate. Mais uma vez, a função "
"<literal>table do elemento set determina o nome "
"da tabela para a coleção. O elemento <literal>key define o nome da "
"coluna de chave estrangeira na tabela de coleção. A função <literal>columnelement define o nome da "
"coluna onde os valores da <literal>String serão armazenados.  "

#. Tag: para
#: tutorial.xml:847
#, no-c-format
msgid "Here is the updated schema:"
msgstr "Segue abaixo o esquema atualizado:  "

#. 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 ""
"Você pode observar que a chave primária da tabela da coleção é na verdade "
"uma chave composta, usando as duas colunas. Isso também implica que cada "
"pessoa não pode ter endereços de e-mail duplicados, o que é exatamente a "
"semântica que precisamos para um set em 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 ""
"Você pode agora tentar adicionar elementos à essa coleção, do mesmo modo que "
"fizemos anteriormente ligando pessoas e eventos. É o mesmo código em 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 ""
"Desta vez não utilizamos uma consulta <emphasis>fetch (busca) "
"para inicializar a coleção. Monitore o log SQL e tente otimizá-lo com árdua "
"busca. "

#. Tag: title
#: tutorial.xml:875
#, no-c-format
msgid "Bi-directional associations"
msgstr "Associações bidirecionais "

#. Tag: para
#: tutorial.xml:877
#, no-c-format
msgid ""
"Next you will map a bi-directional association. You will make the "
"association between person and event work from both sides in Java. The "
"database schema does not change, so you will still have many-to-many "
"multiplicity."
msgstr ""
"Agora iremos mapear uma associação bidirecional. Você fará uma associação "
"entre o trabalho person e event de ambos os lados em Java. O esquema do "
"banco de dados acima não muda, de forma que você continua possuir a "
"multiplicidade muitos-para-muitos. "

#. Tag: para
#: tutorial.xml:885
#, no-c-format
msgid ""
"A relational database is more flexible than a network programming language, "
"in that it does not need a navigation direction; data can be viewed and "
"retrieved in any possible way."
msgstr ""
"Um banco de dados relacional é mais flexível que um linguagem de programação "
"da rede, de maneira que ele não precisa de uma direção de navegação; os "
"dados podem ser visualizados e restaurados de qualquer maneira."

#. Tag: para
#: tutorial.xml:893
#, no-c-format
msgid ""
"First, add a collection of participants to the <literal>Event "
"class:"
msgstr ""
"Primeiramente, adicione uma coleção de participantes à classe "
"<literal>Event:  "

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

#. Tag: para
#: tutorial.xml:900
#, no-c-format
msgid ""
"Now map this side of the association in <literal>Event.hbm.xml."
msgstr ""
"Agora mapeie este lado da associação em <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 ""
"Como você pode ver, esses são mapeamentos <literal>set normais em "
"ambos documentos de mapeamento. Observe que os nomes das colunas em "
"<literal>key e many-to-many estão trocados em "
"ambos os documentos de mapeamento. A adição mais importante feita está na "
"função <literal>inverse=\"true\" no elemento setEvent. "

#. 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 ""
"Isso significa que o Hibernate deve pegar o outro lado, a classe "
"<literal>Person, quando precisar encontrar informação sobre a "
"relação entre as duas entidades. Isso será muito mais fácil de entender "
"quando você analisar como a relação bidirecional entre as entidades é "
"criada. "

#. Tag: title
#: tutorial.xml:923
#, no-c-format
msgid "Working bi-directional links"
msgstr "Trabalhando com links bidirecionais "

#. 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 e um "
"<literal>Event no exemplo unidirecional? Adicionamos uma instância "
"de <literal>Event, da coleção de referências de eventos, à uma "
"instância de <literal>Person. Então, obviamente, se quisermos que "
"este link funcione bidirecionalmente, devemos fazer a mesma coisa para o "
"outro lado, adicionando uma referência de <literal>Person na "
"coleção de um <literal>Event. Essa \"configuração de link de ambos "
"os lados\" é absolutamente necessária e você nunca deve esquecer de fazê-la. "

#. Tag: para
#: tutorial.xml:935
#, no-c-format
msgid ""
"Many developers program defensively and create link management methods to "
"correctly set both sides (for example, in <literal>Person):"
msgstr ""
"Muitos desenvolvedores programam de maneira defensiva e criam métodos de "
"gerenciamento de um link que ajustam-se corretamente em ambos os lados (como "
"por exemplo, em <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 ""
"Observe que os métodos set e get da coleção estão protegidos. Isso permite "
"que classes e subclasses do mesmo pacote continuem acessando os métodos, mas "
"evita que qualquer outra classe, que não esteja no mesmo pacote, acesse a "
"coleção diretamente. Repita os passos para a coleção do outro 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 ""
"E sobre o mapeamento da função <literal>inverse? Para você, e para "
"o Java, um link bidirecional é simplesmente uma questão de configurar "
"corretamente as referências de ambos os lados. O Hibernate, entretanto, não "
"possui informação necessária para ajustar corretamente as instruções "
"<literal>INSERT e UPDATE do SQL (para evitar "
"violações de restrição) e precisa de ajuda para manipular as associações "
"bidirecionais de forma apropriada. Ao fazer um lado da associação com a "
"função <literal>inverse, você instrui o Hibernate para basicamente "
"ignorá-lo, considerando-o uma <emphasis>cópia do outro lado. Isso "
"é o necessário para o Hibernate compreender todas as possibilidades quando "
"transformar um modelo de navegação bidirecional em esquema de banco de dados "
"do SQL. As regras que você precisa lembrar são diretas: todas as associações "
"bidirecionais necessitam que um lado possua a função <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 ""
"Um aplicativo de web do Hibernate utiliza uma <literal>Session e "
"uma <literal>Transaction quase do mesmo modo que um aplicativo "
"autônomo. Entretanto, alguns modelos comuns são úteis. Nós agora criaremos "
"um <literal>EventManagerServlet. Esse servlet lista todos os "
"eventos salvos no banco de dados, e cria um formulário HTML para entrada de "
"novos eventos. "

#. Tag: title
#: tutorial.xml:975
#, no-c-format
msgid "Writing the basic servlet"
msgstr "Criando um 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 ""
"Nós deveremos criar o nosso servket de processamento básico primeiramente. "
"Uma vez que o servlet manuseia somente requisições <literal>GET do "
"HTTP, o método que iremos implementar é <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 ""
"Salve esse 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 ""
"O modelo que estamos aplicando neste código é chamado <emphasis>session-per-"
"request</emphasis>. Quando uma solicitação chega ao servlet, uma nova "
"<literal>Session do Hibernate é aberta através da primeira chamada "
"para <literal>getCurrentSession() em 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() utilize uma nova Session do "
"Hibernate para todas as operações de banco de dados. Utilize uma "
"<literal>Session do Hibernate que seja de interesse à todas as "
"solicitações. Utilize <literal>getCurrentSession(), para que seja "
"vinculado automaticamente à thread atual de Java.  "

#. 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 ""
"Agora, as possíveis ações de uma solicitação serão processadas e uma "
"resposta HTML será renderizada. Já chegaremos nesta parte.  "

#. 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, a unidade de trabalho termina quando o processamento e a "
"renderização são completados. Se ocorrer algum erro durante o processamento "
"ou a renderização, uma exceção será lançada e a transação do banco de dados "
"revertida. Isso completa o modelo <literal>session-per-request. Em "
"vez de usar código de demarcação de transação em todo servlet você pode "
"também criar um filtro servlet. Dê uma olhada no website do Hibernate e do "
"Wiki para maiores informações sobre esse modelo, chamado <emphasis>Sessão "
"Aberta na Visualização</emphasis>. Você precisará disto assim que você "
"considerar renderizar sua visualização no JSP, não apenas num servlet. "

#. Tag: title
#: tutorial.xml:1025
#, no-c-format
msgid "Processing and rendering"
msgstr "Processando e renderizando"

#. 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 ""
"Vamos implementar o processamento da solicitação e renderização da 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 ""
"O estilo deste código misturado com o Java e HTML, não escalariam em um "
"aplicativo mais complexo, tenha em mente que estamos somente ilustrando os "
"conceitos básicos do Hibernate neste tutorial. O código imprime um cabeçalho "
"e nota de rodapé em HTML. Dentro desta página, são impressos um formulário "
"para entrada de evento em HTML e uma lista de todos os evento no banco de "
"dados. O primeiro método é trivial e somente produz um 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 "" "O método <literal>listEvents() utiliza a Session\");\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.