Boa tarde pessoal, já pesquisei bastante e não estou conseguindo trabalhar com JPA na seguinte estrutura de tabelas conforme figura em anexo.
Segue abaixo o script do banco (Mysql):
CREATE TABLE `relacionamento1x1ladoa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descricao` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
CREATE TABLE `relacionamento1x1ladob` (
`id` int(11) NOT NULL,
`descricao` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_1x1` (`id`),
CONSTRAINT `fk_1x1` FOREIGN KEY (`id`) REFERENCES `relacionamento1x1ladoa` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB
As minhas classes anotadas:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author gilson
*/
@Entity
@Table(name = "relacionamento1x1ladoa")
public class Relacionamento1x1ladoa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "descricao")
private String descricao;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "relacionamento1x1ladoa", fetch = FetchType.LAZY)
private Relacionamento1x1ladob relacionamento1x1ladob;
public Relacionamento1x1ladoa() {
}
public Relacionamento1x1ladoa(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Relacionamento1x1ladob getRelacionamento1x1ladob() {
return relacionamento1x1ladob;
}
public void setRelacionamento1x1ladob(Relacionamento1x1ladob relacionamento1x1ladob) {
this.relacionamento1x1ladob = relacionamento1x1ladob;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Relacionamento1x1ladoa)) {
return false;
}
Relacionamento1x1ladoa other = (Relacionamento1x1ladoa) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "beans.Relacionamento1x1ladoa[id=" + id + "]";
}
}
e
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import java.io.Serializable;
import java.lang.annotation.Inherited;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author gilson
*/
@Entity
@Table(name = "relacionamento1x1ladob")
public class Relacionamento1x1ladob implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "descricao")
private String descricao;
@JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
@OneToOne(optional = false, fetch = FetchType.LAZY)
private Relacionamento1x1ladoa relacionamento1x1ladoa;
public Relacionamento1x1ladob() {
}
public Relacionamento1x1ladob(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Relacionamento1x1ladoa getRelacionamento1x1ladoa() {
return relacionamento1x1ladoa;
}
public void setRelacionamento1x1ladoa(Relacionamento1x1ladoa relacionamento1x1ladoa) {
this.relacionamento1x1ladoa = relacionamento1x1ladoa;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Relacionamento1x1ladob)) {
return false;
}
Relacionamento1x1ladob other = (Relacionamento1x1ladob) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "beans.Relacionamento1x1ladob[id=" + id + "]";
}
}
e a classe de teste
import beans.Relacionamento1x1ladoa;
import beans.Relacionamento1x1ladob;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PrincipalRelacionamento1X1 {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("TesteJPAPU");
EntityManager em = emf.createEntityManager();
Relacionamento1x1ladoa ladoa = new Relacionamento1x1ladoa();
ladoa.setDescricao("Descrição lado a.");
Relacionamento1x1ladob ladob = new Relacionamento1x1ladob();
ladob.setDescricao("Descrição lado b.");
ladoa.setRelacionamento1x1ladob(ladob);
ladob.setRelacionamento1x1ladoa(ladoa);
em.getTransaction().begin();
em.persist(ladoa);
em.getTransaction().commit();
}
}
O erro que acontece é este aqui:
[EL Info]: 2010-08-17 15:18:07.831--ServerSession(18450577)--EclipseLink, version: Eclipse Persistence Services - 2.0.2.v20100323-r6872
[EL Info]: 2010-08-17 15:18:08.182--ServerSession(18450577)--file:/C:/Users/gilson.TECHSCORP/Desktop/TesteJPA/src/_TesteJPAPU login successful
[EL Warning]: 2010-08-17 15:18:08.238--UnitOfWork(24061351)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO relacionamento1x1ladob (id, descricao) VALUES (?, ?)
bind => [null, Descrição lado b.]
Query: InsertObjectQuery(beans.Relacionamento1x1ladob[id=null])
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO relacionamento1x1ladob (id, descricao) VALUES (?, ?)
bind => [null, Descrição lado b.]
Query: InsertObjectQuery(beans.Relacionamento1x1ladob[id=null])
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
at PrincipalRelacionamento1X1.main(PrincipalRelacionamento1X1.java:25)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO relacionamento1x1ladob (id, descricao) VALUES (?, ?)
bind => [null, Descrição lado b.]
Query: InsertObjectQuery(beans.Relacionamento1x1ladob[id=null])
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:801)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:867)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:587)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:530)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeCall(AbstractSession.java:914)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:206)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:192)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:335)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:462)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:675)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:589)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:109)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:86)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2898)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1225)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1167)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:197)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:164)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:116)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3260)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1413)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:547)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1518)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:200)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1139)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:84)
... 2 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:792)
... 34 more
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)
Como faço para que o Id gerado na classe do lado a (auto increment) seja exportada para o lado b? já tentei de tudo e não consegui.
Obrigado desde já!!