Pessoal, boa tarde!
Estou começando com java e estou com algumas dúvidas!
Como faço a persistência de duas Entidades em duas tabelas diferentes de forma que seus IDs fique iguais!
Exemplo:
tabela A:
id_A
tabela B:
id_B
fk_id_A
Segue meu código!
Entidade Cliente.java
[code]
@Entity
@Table(name = “tbcliente”)
public class Cliente implements Serializable {
@Id
@Column(name = "IDCLIENTE")
@GeneratedValue
private Integer idCliente;
@JoinColumn(name = "IDPESSOA", referencedColumnName = "IDPESSOA")
@OneToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Pessoa pessoa;
// metodos getters e setters
}[/code]
Entidade Pessoa.java
[code]
@Entity
@Table(name = “tbpessoa”)
public class Pessoa implements Serializable {
@Id
@Column(name = "IDPESSOA")
@GeneratedValue
private Integer idPessoa;
@JoinColumn(name = "IDENDERECO", referencedColumnName = "IDENDERECO")
@OneToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Endereco endereco;
// getters e setters
}[/code]
ClienteBean.java
@Component("clienteBean")
@Scope("session")
public class ClienteBean extends ControlerJsf {
@Autowired
private ClienteService clienteService;
@Autowired
private PessoaService pessoaService;
@Autowired
private EnderecoService enderecoService;
private Cliente cliente;
private List<Cliente> listaCliente;
public ClienteBean() {
super("Cadastro de Clientes", null, "2");
}
public Cliente getCliente() {
if (cliente == null) {
cliente = new Cliente();
cliente.setPessoa(new Pessoa());
cliente.getPessoa().setEndereco(new Endereco());
cliente.getPessoa().setDataCadastro(
new GregorianCalendar().getTime());
}
return cliente;
}
// getters e setters
public void incluir() {
try {
clienteService.incluir(cliente);
addMensagemFaces("Inclusão do Cliente efetuada com sucesso!"
+ "ID Cliente: " + cliente.getIdCliente()
+ " - ID Pessoa: " + cliente.getPessoa().getIdPessoa()
+ " - ID Endereco: "
+ cliente.getPessoa().getEndereco().getIdEndereco());
} catch (Exception e) {
addMensagemFaces("Não foi possivel incluir o Cliente. Motivo: "
+ e.getMessage());
}
}
src/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="punit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
</persistence-unit>
</persistence>
WebContent/WEB-INF/applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
default-lazy-init="true" default-autowire="byName">
<context:component-scan base-package="aplic.meuprojeto"/>
<context:annotation-config />
<bean id="dataSourcePostgre" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.postgresql.Driver" />
<property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/bd" />
<property name="user" value="postgres" />
<property name="password" value="123456" />
<property name="minPoolSize" value="2" />
<property name="maxPoolSize" value="5" />
<property name="maxStatements" value="0" />
<property name="checkoutTimeout" value="180000" />
<property name="idleConnectionTestPeriod" value="250" />
<property name="maxIdleTime" value="180" />
<property name="numHelperThreads" value="5" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="5" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourcePostgre" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
<prop key="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_structured_entries">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
<prop key="hibernate.statement_cache.size">0</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Quando faço a persistência a Tabela Cliente fica com ID: 1 , Pessoa fica com ID: 2 e Endereço fica com ID: 3.
onde deveria ser idCliente = 1, idPessoa = 1 e idEndereço = 1;
o que esta errado? desde-já obrigado!