5
respostas

Como mapear o atributo telefones em xml?

Eu testei o mapeamento usando as anotações do JPA, funcionou perfeitamente tirando a obrigação da inserção de o atributo id em Aluno, porque dava problemas ao utilizar o cpf como chave primária. O problema é quando tento fazer tudo por xml, eu não consigo mapear o atributo telefones nem usando a tag "one-to-many" nem a "element-collection" já que nem são reconhecidas na IDE e lançam uma exceção quando testo o programa e ,por consequência, para fazer meus testes funcionarem eu preciso remover o atributo telefones e tudo relacionado a ele:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd"
    version="2.2">
    <entity class="br.com.alura.escola.dominio.aluno.Aluno" name="Aluno">
        <table name="alunos" />
        <attributes>
            <id name="id">
                <column name="id" nullable="false" />
                <generated-value strategy="IDENTITY" />
            </id>
            <basic name="nome">
                <column name="nome" nullable="false" />
            </basic>
            <embedded name="cpf">
                <attribute-override name="cpf">
                    <column name="cpf" nullable="false" />
                </attribute-override>
            </embedded>
            <embedded name="email">
                <attribute-override name="email">
                    <column name="email" nullable="false" />
                </attribute-override>
            </embedded>
            <!-- Não Funciona (InvalidMappingException)
            <element-collection name="telefones" target-class="br.com.alura.escola.dominio.aluno.Telefone">
                <collection-table name="telefones">
                    <join-column name="aluno_id" nullable="false"/>
                </collection-table>
                <column name="telefone" nullable="false"/>
            </element-collection>
            -->
            <!-- Não Funciona (InvalidMappingException)
                <one-to-many name="telefones" fetch="LAZY">
                    <cascade>
                        <cascade-all/>
                    </cascade>
                    <join-column name="aluno_id" nullable="false"/>
                </one-to-many>
            -->
        </attributes>
    </entity>

    <embeddable class="br.com.alura.escola.dominio.aluno.CPF">
        <attributes>
            <basic name="cpf">
                <column name="cpf" nullable="false" />
            </basic>
        </attributes>
    </embeddable>

    <embeddable class="br.com.alura.escola.dominio.aluno.Email">
        <attributes>
            <basic name="email">
                <column name="email" nullable="false" />
            </basic>
        </attributes>
    </embeddable>
    
    <embeddable class="br.com.alura.escola.dominio.aluno.Telefone">
        <attributes>
            <basic name="ddd">
                <column name="ddd" nullable="false"/>
            </basic>
            <basic name="numero">
                <column name="numero" nullable="false"/>
            </basic>
        </attributes>
    </embeddable>
</entity-mappings>
5 respostas

Olá, Sidnei! Como vai?

Poderia compartilhar o log completo do error quando subiu o InvalidMappingException?

![](Erro de compilação nas tags element-collection e column )

org.hibernate.boot.InvalidMappingException: Could not parse mapping document: C:\Users\juniorsi\Documents\workspace-spring-tool-suite-4-4.19.0.RELEASE\escola\target\classes\META-INF\orm.xml (INPUT_STREAM)
    at org.hibernate.boot.jaxb.internal.InputStreamXmlSource.doBind(InputStreamXmlSource.java:46)
    at org.hibernate.boot.jaxb.internal.InputStreamXmlSource.doBind(InputStreamXmlSource.java:38)
    at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:79)
    at org.hibernate.boot.model.process.internal.ScanningCoordinator.applyScanResultsToManagedResources(ScanningCoordinator.java:208)
    at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:82)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:107)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:266)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:187)
    at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:75)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at br.com.alura.escola.infraestrutura.AlunoRepositoryJPATest.setUp(AlunoRepositoryJPATest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:126)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeEachMethod(TimeoutExtension.java:76)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeMethodInExtensionContext(ClassBasedTestDescriptor.java:481)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$synthesizeBeforeEachMethodAdapter$18(ClassBasedTestDescriptor.java:466)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachMethods$2(TestMethodTestDescriptor.java:169)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:197)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:197)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachMethods(TestMethodTestDescriptor.java:166)

Dessa forma funciona?

<element-collection name="telefones" target-class="br.com.alura.escola.dominio.aluno.Telefone">
    <collection-table name="telefones">
        <join-column name="aluno_id" nullable="false"/>
    </collection-table>
    <column name="ddd" nullable="false"/>
    <column name="numero" nullable="false"/>
</element-collection>

Não compila de jeito nenhum e continua retornando o mesmo stacktrace. XML com erro de compilação nas tags element-collection e column

<element-collection name="telefones" target-class="br.com.alura.escola.dominio.aluno.Telefone">
    <collection-table name="telefones">
        <join-column name="aluno_id" nullable="false"/>
    </collection-table>
</element-collection>

<embeddable class="br.com.alura.escola.dominio.aluno.Telefone">
    <attributes>
        <basic name="ddd">
            <column name="ddd" nullable="false"/>
        </basic>
        <basic name="numero">
            <column name="numero" nullable="false"/>
        </basic>
    </attributes>
</embeddable>

Neste exemplo, a classe Telefone é definida como um tipo incorporável (<embeddable>), e a coleção de telefones é mapeada como uma coleção de elementos (<element-collection>). As colunas ddd e numero são definidas dentro da tag <embeddable>, e não dentro da tag <element-collection>.