问题描述:

Fellows,

I'm facing an issue during hibernate storing with merge() method. Let me see if you can help me. Having said that, I'll post my code below.

1) DDL SQL

Here is the involved table defs (some columns were ommited because are only regular data):

TABLE proposta (

idProposta INT(11) NOT NULL AUTO_INCREMENT,

idBeneficio INT(11) NOT NULL,

idTabela INT NULL,

idOperacao INT NOT NULL,

...

TABLE conta_bancaria (

idContaBancaria INT NOT NULL AUTO_INCREMENT,

idBanco INT NOT NULL,

idProposta INT NOT NULL,

idBeneficio INT NOT NULL,

...

TABLE banco (

idBanco INT(11) NOT NULL AUTO_INCREMENT,

nmNomeBanco VARCHAR(60) NULL DEFAULT NULL,

cdBanco VARCHAR(5) NULL DEFAULT NULL,

nmNomeCompleto VARCHAR(90) NULL,

dsSite VARCHAR(256) NULL,

blAtivo INT NULL DEFAULT NULL,

PRIMARY KEY (`idBanco`)

2) Code

2.1) Entity Mappings

@Entity

@Table(name="Proposta")

public class Proposta extends GenericEntity<Proposta>{

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "idProposta")

private Integer idProposta;

@OneToOne(cascade = CascadeType.ALL, mappedBy="proposta", fetch = FetchType.LAZY, optional=true)

@JoinColumn(name = "idProposta", referencedColumnName="idProposta")

@Basic(optional=true)

private ContaBancaria contaRecebimento;

@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)

@JoinColumn(name = "idBeneficio", referencedColumnName="idBeneficio")

private Beneficio beneficio;

@OneToOne(cascade=CascadeType.ALL)

@JoinColumn(name = "idOperacao", referencedColumnName="idOperacao")

private Operacao operacao;

...

@Entity

@Table(name="Conta_Bancaria")

public class ContaBancaria extends GenericEntity<ContaBancaria>{

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "idContaBancaria")

private Integer idContaBancaria;

@ManyToOne(cascade = CascadeType.ALL)

@JoinColumn(name = "idBanco")

private Banco banco;

@OneToOne

@PrimaryKeyJoinColumn

private Proposta proposta;

@OneToOne

@PrimaryKeyJoinColumn

private Beneficio beneficio;

...

2.2) Controller

@ManagedBean("propostaBean")

@ViewScoped

public class PropostaBean extends GenericController {

@Inject

private PropostaService propostaService;

/** Aba Cadastro Proposta **/

private Pessoa pessoa;

private Beneficio beneficio;

private Proposta proposta;

private List<Banco> bancos;

private Integer idBancoSelected;

private Integer idOperacaoSelected;

private List<Operacao> operacoes;

public PropostaBean() {

refreshBean();

}

@PostConstruct

private void refreshBean(){

this.pessoa = new Pessoa();

this.beneficio = new Beneficio();

this.proposta = new Proposta();

this.filtroBenProp = new FiltroBeneficioProposta();

this.resultadoBuscaBeneficio = new ArrayList<PessoaBeneficioDTO>();

this.bancos = new ArrayList<Banco>();

this.operacoes = new ArrayList<Operacao>();

}

public String salvarProposta(){

String method = "salvarProposta";

long startTime = startMethod(method);

Banco banco = null;

for (Banco b : bancos) {

if(b.getIdBanco() == idBancoSelected){

banco = b;

}

}

Operacao operacao = null;

for (Operacao op : operacoes) {

if(op.getIdOperacao() == idOperacaoSelected){

operacao = op;

this.proposta.setOperacao(operacao);

}

}

System.out.println("Operacao = ["+operacao+"], idOperacaoSelected ["+idOperacaoSelected+"]");

System.out.println("Conta Bancaria = ["+proposta.getContaRecebimento()+"]");

this.proposta.setBeneficio(beneficio);

try {

if(proposta.getContaRecebimento().getAgencia() == null){

proposta.setContaRecebimento(null);

}

this.proposta = propostaService.salvarProposta(proposta);

proposta.setContaRecebimento(new ContaBancaria());

FacesUIHelper.addSucessMessage("Proposta no ["+proposta.getNpi()+"] cadastrada com sucesso");

} catch (BusinessException e) {

e.printStackTrace();

FacesUIHelper.addErrorMessage(e.getMessage());

}

leaveMethod(startTime, method);

return "/views/cadastro/cadastroProposta";

}

}

2.3) Service

@Service("propostaService")

@Transactional

public class PropostaServiceImpl extends GenericServiceImpl<Proposta> implements Serializable, PropostaService {

public static final String USUARIO_DEFAULT = "SYSTEM";

@Inject

private PropostaDAO<Proposta> propostaDAO;

@Inject

private OperacaoDAO<Operacao> operacaoDAO;

@Inject

private BeneficioDAO<Beneficio> beneficioDAO;

@Inject

private TipoOperacaoDAO<TipoOperacao> tipoOperacaoDAO;

@Inject

private ParametroSistemaDAO<ParametroSistema> parametroSistemaDAO;

@Override

public Proposta salvarProposta(Proposta p) throws BusinessException {

String method = "salvarProposta";

long startTime = startMethod(method);

Proposta prop = null;

if(p.getIdProposta() == null){

try {

Integer npi = parametroSistemaDAO.getSequenceValue("SEQ_NPI");

p.setNpi(npi);

Date dt = new Date(System.currentTimeMillis());

p.setDataProposta(dt);

p.setDataStatus(dt);

p.setStatus(Proposta.CADASTRADA);

p.setUsuarioResponsavel(USUARIO_DEFAULT);

prop = propostaDAO.saveOrUpdate(p);

} catch (DAOException e) {

throw new BusinessException(e);

}

}else {

prop = propostaDAO.saveOrUpdate(p);

}

leaveMethod(startTime, method);

return prop;

}

}

2.4) DAO

@Repository("genericDao")

public abstract class GenericDAOImpl<T> implements GenericDAO<T> {

protected static Logger logger;

@PersistenceContext

protected EntityManager entityManager;

protected String className;

private Class< T > type;

public GenericDAOImpl() {

Type t = getClass().getGenericSuperclass();

ParameterizedType pt = (ParameterizedType) t;

type = (Class) pt.getActualTypeArguments()[0];

this.logger = LoggerFactory.getLogger(getClass());

this.className = this.getClass().getName();

}

@Transactional

public T save(T entity) throws DAOException {

entityManager.persist(entity);

return entity;

}

@Transactional

public T update(T entity) {

entityManager.merge(entity);

return entity;

}

@TransactionAttribute(TransactionAttributeType.REQUIRED)

public T saveOrUpdate(T entity){

entityManager.merge(entity);

return entity;

}

@Transactional

public Collection<T> saveOrUpdateAll(Collection<T> entities) {

for(T element: entities) {

entityManager.merge(element);

}

return entities;

}

@Transactional

public void delete(T entity) {

entityManager.remove(entity);

}

@Transactional

public void deleteAll(List<T> list) {

for(T element: list) {

entityManager.remove(element);

}

}

@SuppressWarnings("unchecked")

public List<T> listAll() {

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<T> c = cb.createQuery(type);

Root<T> genericObject = c.from(type);

TypedQuery<T> typedQuery = entityManager.createQuery(c);

List<T> resultList = (List<T>) typedQuery.getResultList();

return resultList;

}

public T findById(long id) {

T result =(T) entityManager.find(type, id);

return result;

}

public T findById(Serializable id) {

T result =(T) entityManager.find(type, id);

return result;

}

public EntityManager getEntityManager() {

return entityManager;

}

public void setEntityManager(EntityManager entityManager) {

this.entityManager = entityManager;

}

}

When I call merge for proposta instance (which is not created yet), even when I mark (or at least it supposed to be marked) Proposta.ContaBancaria as an optional relationship, hibernate tries to insert it also. Here it's hibernate logs:

04:47:33,410 INFO [stdout] Hibernate:

04:47:33,410 INFO [stdout] insert

04:47:33,411 INFO [stdout] into

04:47:33,411 INFO [stdout] Proposta

04:47:33,411 INFO [stdout] (idBeneficio, dtEnvioFisico, dtPagamento, dtPagamentoComissao, dtProposta, dtStatus, cdDocExterno, tpMeioPagamento, cdNpi, nrLinhasAtual, nrNumParcelas, idOperacao, status, nmUsuario, vlBrutoConsiderado, vlDescontos, vlLiquidoLiberado, vlLiquidoBeneficio, vlMargemLivre, vlValorParcela)

04:47:33,413 INFO [stdout] values

04:47:33,413 INFO [stdout] (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

04:47:33,502 INFO [stdout] Hibernate:

04:47:33,502 INFO [stdout] insert

04:47:33,502 INFO [stdout] into

04:47:33,503 INFO [stdout] Conta_Bancaria

04:47:33,503 INFO [stdout] (nrAgencia, blAtivo, idBanco, nrDigitoAgencia, nrDigitoConta, nrConta, blPoupanca, nrTipo)

04:47:33,504 INFO [stdout] values

04:47:33,504 INFO [stdout] (?, ?, ?, ?, ?, ?, ?, ?)

Then I get this error following:

04:47:33,552 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] SQL Error: 1048, SQLState: 23000

04:47:33,553 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] Column 'idBanco' cannot be null

04:47:34,352 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] #{propostaBean.salvarProposta}: org.springframework.dao.DataIntegrityViolationException: Column 'idBanco' cannot be null; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Column 'idBanco' cannot be null: javax.faces.FacesException: #{propostaBean.salvarProposta}: org.springframework.dao.DataIntegrityViolationException: Column 'idBanco' cannot be null; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Column 'idBanco' cannot be null

at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]

at org.primefaces.application.DialogActionListener.processAction(DialogActionListener.java:45) [primefaces-4.0.jar:4.0]

at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at javax.faces.component.UIData.broadcast(UIData.java:1093) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:]

at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]

at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]

at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]

at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98) [primefaces-4.0.jar:4.0]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]

at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]

at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]

at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]

at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]

at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]

at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_21]

Caused by: javax.faces.el.EvaluationException: org.springframework.dao.DataIntegrityViolationException: Column 'idBanco' cannot be null; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Column 'idBanco' cannot be null

at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:]

... 26 more

Caused by: org.springframework.dao.DataIntegrityViolationException: Column 'idBanco' cannot be null; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Column 'idBanco' cannot be null

at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:188) [spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:154) [spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) [spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at com.sun.proxy.$Proxy110.saveOrUpdate(Unknown Source)

at br.com.centralemprestimos.sisat.service.PropostaServiceImpl.salvarProposta(PropostaServiceImpl.java:65) [classes:]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]

at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]

at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at com.sun.proxy.$Proxy113.salvarProposta(Unknown Source)

at br.com.centralemprestimos.sisat.mbean.PropostaBean.salvarProposta(PropostaBean.java:184) [classes:]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]

at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]

at org.apache.el.parser.AstValue.invoke(AstValue.java:262) [jbossweb-7.0.13.Final.jar:]

at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) [jbossweb-7.0.13.Final.jar:]

at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:]

at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]

... 27 more

Caused by: org.hibernate.exception.ConstraintViolationException: Column 'idBanco' cannot be null

at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:74) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at com.sun.proxy.$Proxy78.executeUpdate(Unknown Source)

at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:55) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2757) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3268) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:304) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:128) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.ejb.event.EJB3MergeEventListener.saveWithGeneratedId(EJB3MergeEventListener.java:71) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:422) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:342) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:304) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:259) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:790) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:774) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.spi.CascadingAction$6.cascade(CascadingAction.java:288) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:462) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:395) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:304) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:259) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:86) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:781) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:766) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:770) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:867) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]

at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]

at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:257) [spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at com.sun.proxy.$Proxy102.merge(Unknown Source)

at br.com.mobinn.fmwk.persistence.GenericDAOImpl.saveOrUpdate(GenericDAOImpl.java:60) [classes:]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]

at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]

at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]

at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) [spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]

... 59 more

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'idBanco' cannot be null

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [rt.jar:1.7.0_21]

at java.lang.reflect.Constructor.newInstance(Constructor.java:525) [rt.jar:1.7.0_21]

at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.Util.getInstance(Util.java:386) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377) [mysql-connector-java-5.1.26.jar:]

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361) [mysql-connector-java-5.1.26.jar:]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]

at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]

at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

... 106 more

But it shouldn't be inserting ContaBancaria because it's empty and optional. It's not null because it's being rendered in view, but all fields are empty as this print shows:

04:47:33,145 INFO [stdout] Conta Bancaria = [ContaBancaria [idContaBancaria=null, agencia=, digitoAgencia=null, numeroConta=null, digitoConta=, tipo=null, poupanca=0, ativo=null]]

Is there any mapping errors ? What am I doing wrong ?

Thanks in advance.

网友答案:

In your mapping, you specified the property cascade with value Cascade.All, which means the ContaBancaria must be inserted/updated/deleted in cascade when the parent entity Proposta is inserted/updated/deleted. The optional attribute set to "true" means that ContaBancaria field in Proposta can be null when inserting or updating, but given that in your case ContaBancaria is not null (but empty), hibernate understands that there is an object (not null) to insert in cascade.

相关阅读:
Top