📄 session_api.po
字号:
"there is no matching database row. If the class is mapped with a proxy, ""<literal>load()</literal> just returns an uninitialized proxy and does not ""actually hit the database until you invoke a method of the proxy. This ""behaviour is very useful if you wish to create an association to an object ""without actually loading it from the database. It also allows multiple ""instances to be loaded as a batch if <literal>batch-size</literal> is ""defined for the class mapping."msgstr """Repare que <literal>load()</literal> irá lançar uma exceção irrecuperável se ""não houver na tabela no banco de dados um registro que combine. Se a classe ""for mapeada com um proxy, <literal>load()</literal> simplesmente retorna um ""proxy não inicializado e realmente não chamará o banco de dados até que um ""método do proxy seja invocado. Esse comportamento é muito útil se deseja-se ""criar uma associação com um objeto sem que realmente o carregue do bando de ""dados. Isto também permite que sejam carregadas múltiplas instâncias como um ""grupo se <literal>batch-size</literal> estiver para o mapeamento da classe."#. Tag: para#: session_api.xml:179#, no-c-formatmsgid """If you are not certain that a matching row exists, you should use the ""<literal>get()</literal> method, which hits the database immediately and ""returns null if there is no matching row."msgstr """Se você não tiver certeza da existencia do registro no banco, você deve usar ""o metodo <literal>get()</literal>, que consulta o banco imediantamente e ""retorna um null se não existir o registro."#. Tag: programlisting#: session_api.xml:185#, no-c-formatmsgid """<![CDATA[Cat cat = (Cat) sess.get(Cat.class, id);\n""if (cat==null) {\n"" cat = new Cat();\n"" sess.save(cat, id);\n""}\n""return cat;]]>"msgstr ""#. Tag: para#: session_api.xml:187#, no-c-formatmsgid """You may even load an object using an SQL <literal>SELECT ... FOR UPDATE</""literal>, using a <literal>LockMode</literal>. See the API documentation for ""more information."msgstr """Também pode-se carregar um objeto usando <literal>SELECT ... FOR UPDATE</""literal>, usando um <literal>LockMode</literal>. Veja a documentação da API ""para maiores informações."#. Tag: programlisting#: session_api.xml:192#, no-c-formatmsgid "<![CDATA[Cat cat = (Cat) sess.get(Cat.class, id, LockMode.UPGRADE);]]>"msgstr ""#. Tag: para#: session_api.xml:194#, no-c-formatmsgid """Note that any associated instances or contained collections are ""<emphasis>not</emphasis> selected <literal>FOR UPDATE</literal>, unless you ""decide to specify <literal>lock</literal> or <literal>all</literal> as a ""cascade style for the association."msgstr """Note that any associated instances or contained collections are ""<emphasis>not</emphasis> selected <literal>FOR UPDATE</literal>, unless you ""decide to specify <literal>lock</literal> or <literal>all</literal> as a ""cascade style for the association."#. Tag: para#: session_api.xml:201#, no-c-formatmsgid """It is possible to re-load an object and all its collections at any time, ""using the <literal>refresh()</literal> method. This is useful when database ""triggers are used to initialize some of the properties of the object."msgstr """O recarregamento de um objeto e todas as suas coleções é possível a qualquer ""momento, usando o método <literal>refresh()</literal>. Util quando as ""triggers do banco de dados são usados para inicializar algumas propriedades ""do objeto."#. Tag: programlisting#: session_api.xml:207#, no-c-formatmsgid """<![CDATA[sess.save(cat);\n""sess.flush(); //force the SQL INSERT\n""sess.refresh(cat); //re-read the state (after the trigger executes)]]>"msgstr ""#. Tag: para#: session_api.xml:209#, no-c-formatmsgid """An important question usually appears at this point: How much does Hibernate ""load from the database and how many SQL <literal>SELECT</literal>s will it ""use? This depends on the <emphasis>fetching strategy</emphasis> and is ""explained in <xref linkend=\"performance-fetching\"/>."msgstr """Uma importante questão geralmente aparece neste ponto: O quanto Hibernate ""carrega do banco de dados e quantos SQL <literal>SELECT</literal> ele irá ""usar? Isto depende da estratégia de <emphasis>recuperação</emphasis>usada e ""explicada na <xref linkend=\"performance-fetching\"/>."#. Tag: title#: session_api.xml:219#, no-c-formatmsgid "Querying"msgstr "Consultando"#. Tag: para#: session_api.xml:221#, no-c-formatmsgid """If you don't know the identifiers of the objects you are looking for, you ""need a query. Hibernate supports an easy-to-use but powerful object oriented ""query language (HQL). For programmatic query creation, Hibernate supports a ""sophisticated Criteria and Example query feature (QBC and QBE). You may also ""express your query in the native SQL of your database, with optional support ""from Hibernate for result set conversion into objects."msgstr """Se o identificador do objeto que se está buscando não for conhecido, uma ""consulta será necessária. O Hibernate suporta uma linguagem de consulta ""(HQL) orientada a objetos fácil mas poderosa. Para criação via programação ""de consultas, o Hibernate suporta características sofisticadas de consulta ""por Critério e Exemplo (QBCe QBE). Pode-se também expressar a consulta por ""meio de SQL nativa do banco de dados, com suporte opcional do Hibernate para ""conversão do conjunto de reultados em objetos."#. Tag: title#: session_api.xml:231#, no-c-formatmsgid "Executing queries"msgstr "Executando consultas"#. Tag: para#: session_api.xml:233#, no-c-formatmsgid """HQL and native SQL queries are represented with an instance of <literal>org.""hibernate.Query</literal>. This interface offers methods for parameter ""binding, result set handling, and for the execution of the actual query. You ""always obtain a <literal>Query</literal> using the current <literal>Session</""literal>:"msgstr """Consultas HQL e SQL nativa são representadas por uma instância de ""<literal>org.hibernate.Query</literal>. Esta interface oferece métodos para ""associação de parâmetros, tratamento de conjunto de resultados, e para a ""execução de consultas reais. Você pode obter uma <literal>Query</literal> ""usando a <literal>Session</literal> atual:"#. Tag: programlisting#: session_api.xml:240#, no-c-formatmsgid """<![CDATA[List cats = session.createQuery(\n"" \"from Cat as cat where cat.birthdate < ?\")\n"" .setDate(0, date)\n"" .list();\n""\n""List mothers = session.createQuery(\n"" \"select mother from Cat as cat join cat.mother as mother where cat.name ""= ?\")\n"" .setString(0, name)\n"" .list();\n""\n""List kittens = session.createQuery(\n"" \"from Cat as cat where cat.mother = ?\")\n"" .setEntity(0, pk)\n"" .list();\n""\n""Cat mother = (Cat) session.createQuery(\n"" \"select cat.mother from Cat as cat where cat = ?\")\n"" .setEntity(0, izi)\n"" .uniqueResult();]]\n""\n""Query mothersWithKittens = (Cat) session.createQuery(\n"" \"select mother from Cat as mother left join fetch mother.kittens\");\n""Set uniqueMothers = new HashSet(mothersWithKittens.list());]]>"msgstr ""#. Tag: para#: session_api.xml:242#, no-c-formatmsgid """A query is usually executed by invoking <literal>list()</literal>, the ""result of the query will be loaded completely into a collection in memory. ""Entity instances retrieved by a query are in persistent state. The ""<literal>uniqueResult()</literal> method offers a shortcut if you know your ""query will only return a single object. Note that queries that make use of ""eager fetching of collections usually return duplicates of the root objects ""(but with their collections initialized). You can filter these duplicates ""simply through a <literal>Set</literal>."msgstr """Geralmente uma consulta é executada ao invocar <literal>list()</literal>, o ""resultado da consulta será carregado completamente em uma coleção na ""memória. Instâncias de entidades recuperadas por uma consulta estão no ""estado persistente. O <literal>uniqueResult()</literal> oferece um atalho se ""você souber de previamente que a consulta retornará apenas um único objeto. ""Repare que consultas que fazem uso de buscas de coleções de forma ansiosa ""(eager) geralmente retornam duplicatas dos objetos raiz ( mas com suas ""coleções inicializadas ). Pode-se filtrar estas duplicatas através de um ""simples <literal>Set</literal>."#. Tag: title#: session_api.xml:254#, no-c-formatmsgid "Iterating results"msgstr "Interagindo com resultados"#. Tag: para#: session_api.xml:256#, no-c-formatmsgid """Occasionally, you might be able to achieve better performance by executing ""the query using the <literal>iterate()</literal> method. This will only ""usually be the case if you expect that the actual entity instances returned ""by the query will already be in the session or second-level cache. If they ""are not already cached, <literal>iterate()</literal> will be slower than ""<literal>list()</literal> and might require many database hits for a simple ""query, usually <emphasis>1</emphasis> for the initial select which only ""returns identifiers, and <emphasis>n</emphasis> additional selects to ""initialize the actual instances."msgstr """Ocasionalmente, deves-se ser capaz de atingir performances melhores com a ""execução de consultas usando o método <literal>iterate()</literal>. ""Geralmente isso será o caso esperado apenas se as instâncias dos entidades ""reais retornadas pela consulta já estiverem na sessão ou no caché de segundo ""nível. Caso elas ainda não tenham sido armazenadas, <literal>iterate()</""literal> será mais devagar do que <literal>list()</literal> e pode ser ""necessário vários acessos ao banco de dados para um simples consulta, ""geralmente <emphasis>1</emphasis> para a seleção inicial que retorna apenas ""identificadores, e <emphasis>n</emphasis> consultas adicionais para ""inicializar as instâncias reais."#. Tag: programlisting#: session_api.xml:268#, no-c-formatmsgid """<![CDATA[// fetch ids\n""Iterator iter = sess.createQuery(\"from eg.Qux q order by q.likeliness\").""iterate();\n""while ( iter.hasNext() ) {\n"" Qux qux = (Qux) iter.next(); // fetch the object\n"" // something we couldnt express in the query\n"" if ( qux.calculateComplicatedAlgorithm() ) {\n"" // delete the current instance\n"" iter.remove();\n"" // dont need to process the rest\n"" break;\n"" }\n""}]]>"msgstr ""#. Tag: title#: session_api.xml:272#, no-c-formatmsgid "Queries that return tuples"msgstr "Consultas que retornam tuplas"#. Tag: para#: session_api.xml:274#, no-c-formatmsgid """Hibernate queries sometimes return tuples of objects, in which case each ""tuple is returned as an array:"msgstr """Algumas vezes as consultas do Hibernate retornam tuplas de objetos, nesse ""caso cada tupla é retornada como um array:"#. Tag: programlisting#: session_api.xml:279#, no-c-formatmsgid """<![CDATA[Iterator kittensAndMothers = sess.createQuery(\n"" \"select kitten, mother from Cat kitten join kitten.mother mother""\")\n"" .list()\n"" .iterator();\n""\n""while ( kittensAndMothers.hasNext() ) {\n"" Object[] tuple = (Object[]) kittensAndMothers.next();\n"" Cat kitten = (Cat) tuple[0];\n"" Cat mother = (Cat) tuple[1];\n"" ....\n""}]]>"msgstr ""#. Tag: title#: session_api.xml:284#, no-c-formatmsgid "Scalar results"msgstr "Resultados escalares"#. Tag: para#: session_api.xml:286#, no-c-formatmsgid """Queries may specify a property of a class in the <literal>select</literal> ""clause. They may even call SQL aggregate functions. Properties or aggregates ""are considered \"scalar\" results (and not entities in persistent state)."msgstr """Consultas devem especificar uma propriedade da classe na clausula ""<literal>select</literal>. Elas também podem chamar funções SQL de ""agregaçãos. Propriedades ou agregações são considerados resultados agregados ""( e não entidades no estado persistente)."#. Tag: programlisting#: session_api.xml:292#, no-c-formatmsgid """<![CDATA[Iterator results = sess.createQuery(\n"" \"select cat.color, min(cat.birthdate), count(cat) from Cat cat \" ""+\n"" \"group by cat.color\")\n"" .list()\n"" .iterator();\n""\n""while ( results.hasNext() ) {\n"" Object[] row = (Object[]) results.next();\n"" Color type = (Color) row[0];\n"" Date oldest = (Date) row[1];\n"" Integer count = (Integer) row[2];\n"" .....\n""}]]>"msgstr ""#. Tag: title#: session_api.xml:297#, no-c-formatmsgid "Bind parameters"msgstr "Bind parameters"#. Tag: para#: session_api.xml:299#, no-c-formatmsgid """Methods on <literal>Query</literal> are provided for binding values to named ""parameters or JDBC-style <literal>?</literal> parameters. <emphasis>Contrary ""to JDBC, Hibernate numbers parameters from zero.</emphasis> Named parameters ""are identifiers of the form <literal>:name</literal> in the query string. ""The advantages of named parameters are:"msgstr """Methods on <literal>Query</literal> are provided for binding values to named ""parameters or JDBC-style <literal>?</literal> parameters. <emphasis>Contrary ""to JDBC, Hibernate numbers parameters from zero.</emphasis> Named parameters ""are identifiers of the form <literal>:name</literal> in the query string. ""The advantages of named parameters are:"
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -