1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Problema co relacionamento OneToMany

Boa noite.

Tenho três tabelas no meu banco: Maquina, Peca e PecaMaq.

Uma Maquina possui várias Peca e a tabela PecaMaq possui as chaves estrangeiras das duas.

A dúvida é como fazer esse relacionamento, pois do jeito que estou fazendo não está dando certo.

Abaixo posto as minhas entidades e o erro:

package modelo.entidades;

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

@Entity
public class Maquina {

    @Id
    private int cdMaquina;

    @Column
    private String nmMaq;
    @Column
    private String marcaMaq;
    @Column
    private String sistemaOperac;
    @Column
    private String sistemaOperacLicen;
    @Column
    private String ip;
    @Column
    private String estabNobreak;

    @OneToOne
    @JoinColumn(name="cdLocalidade")
    private Localidade localidade;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, targetEntity=Peca.class)
    @JoinTable(name="PecaMaq", joinColumns={@JoinColumn(name="cdMaquina", referencedColumnName="cdMaquina")}, inverseJoinColumns={@JoinColumn(name="cdPeca", referencedColumnName="cdPeca")})
    private List peca;


    private Date dataBaixa;    

// Getters ans Setters...
package modelo.entidades;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

@Entity
public class Peca {

    @Id
    @GeneratedValue
    private long cdPeca;

    @Column
    private String nmPeca;

//Esse relacionamento é com outra tabela
    @OneToOne
    @JoinColumn(name="cdTpPeca")
    private TpPeca tpPeca;
// Getters ans Setters...
package modelo.entidades;

public class PecaMaq {

    private long cdPecaMaq;
    private Maquina cdMaquina;
    private Peca cdPeca;

    // Getters ans Setters...
0 [main] INFO  org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.5.0-Final
11 [main] INFO  org.hibernate.cfg.Environment - Hibernate 3.5.0-Final
13 [main] INFO  org.hibernate.cfg.Environment - hibernate.properties not found
19 [main] INFO  org.hibernate.cfg.Environment - Bytecode provider name : javassist
23 [main] INFO  org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
114 [main] INFO  org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
122 [main] INFO  org.hibernate.ejb.Version - Hibernate EntityManager 3.5.0-Final
386 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Peca
415 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Peca on table Peca
461 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Impressora
461 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Impressora on table Impressora
469 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Setor
469 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Setor on table Setor
470 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Maquina
470 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Maquina on table Maquina
505 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Local
505 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Local on table Local
507 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.Localidade
507 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.Localidade on table Localidade
509 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: modelo.entidades.TpPeca
509 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity modelo.entidades.TpPeca on table TpPeca
553 [main] INFO  org.hibernate.cfg.AnnotationConfiguration - Hibernate Validator not found: ignoring
570 [main] INFO  org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
576 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
576 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
576 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: true
582 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/insg
582 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****, autocommit=true, release_mode=auto}
796 [main] INFO  org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.5.34
796 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.18 ( Revision: tonci.grgin@oracle.com-20110930151701-jfj14ddfq48ifkfq )
818 [main] INFO  org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
823 [main] INFO  org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
824 [main] INFO  org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
824 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
824 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
824 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
824 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Connection release mode: auto
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
825 [main] INFO  org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
827 [main] INFO  org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
827 [main] INFO  org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: enabled
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Query cache: disabled
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
827 [main] INFO  org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
830 [main] INFO  org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
831 [main] INFO  org.hibernate.cfg.SettingsFactory - Statistics: disabled
831 [main] INFO  org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
831 [main] INFO  org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
831 [main] INFO  org.hibernate.cfg.SettingsFactory - Named query checking : enabled
831 [main] INFO  org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
853 [main] INFO  org.hibernate.impl.SessionFactoryImpl - building session factory
1054 [main] INFO  org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
1058 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - Running hbm2ddl schema update
1058 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - fetching database metadata
1058 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - updating schema
1082 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.impressora
1082 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [cdlocalidade, serie, cdimpressora, databaixa, compart, modelo, ip]
1082 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [cdlocalidade]
1082 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [fk7e0284fffc1cedf8, primary]
1092 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.local
1092 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [nmlocal, cdlocal]
1092 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: []
1092 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary]
1102 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.localidade
1102 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [cdlocalidade, cdsetor, nmlocalidade, cdlocal]
1102 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [cdsetor, cdlocal]
1102 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary, cdlocal, cdsetor_idx]
1116 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.maquina
1116 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [cdlocalidade, sistemaoperac, marcamaq, nmmaq, databaixa, estabnobreak, cdmaquina, ip, sistemaoperaclicen]
1116 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [localidade]
1116 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [cdlocalidade, primary]
1123 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.peca
1123 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [nmpeca, cdpeca, cdtppeca]
1123 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [cdtppeca]
1123 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary, cdtppeca_idx]
1132 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.pecamaq
1132 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [cdpeca, cdpecamaq, cdmaquina]
1132 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: [fk39ec572ae5d3d088, fk39ec572a55d265e6]
1132 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [cdpeca_idx, primary, fk39ec572ae5d3d088, cdmaquina_idx, fk39ec572a55d265e6]
1139 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.setor
1140 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [nmsetor, cdsetor]
1140 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: []
1140 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary]
1147 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: insg.tppeca
1147 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [nmtppeca, cdtppeca]
1147 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: []
1147 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary]
1148 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - schema update complete
1223 [main] INFO  org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
1223 [main] INFO  org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
1284 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Local.hbm.xml
1314 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Local -> LOCAL
1318 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Localidade.hbm.xml
1333 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Localidade -> LOCALIDADE
1333 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Setor.hbm.xml
1343 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Setor -> SETOR
1344 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Impressora.hbm.xml
1353 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Impressora -> IMPRESSORA
1354 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/TpPeca.hbm.xml
1360 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.TpPeca -> TPPECA
1360 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Maquina.hbm.xml
1369 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Maquina -> MAQUINA
1369 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping collection: modelo.entidades.Maquina.peca -> MAQUINA
1370 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/Peca.hbm.xml
1376 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.Peca -> PECA
1376 [main] INFO  org.hibernate.cfg.Configuration - Reading mappings from resource : modelo/entidades/mappings/PecaMaq.hbm.xml
1381 [main] INFO  org.hibernate.cfg.HbmBinder - Mapping class: modelo.entidades.PecaMaq -> PECAMAQ
1382 [main] INFO  org.hibernate.cfg.Configuration - Configured SessionFactory: sessionFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.MappingException: Foreign key (FK5CC80204E5D3D088:MAQUINA [CDMAQUINA])) must have same number of columns as the referenced primary key (MAQUINA [CDMAQUINA,idx])
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:113)
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:96)
    at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1354)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1261)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1377)
    at modelo.dao.DaoResource.<init>(DaoResource.java:30)
    at modelo.dao.MaquinaDao.<clinit>(MaquinaDao.java:12)

Aguardo a ajuda de vocês.

  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

1 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags hibernate java ou faça a sua própria pergunta.