Erro ao salvar entidade usando Hibernate

0 respostas
rafael.espiritosanto

Olá!

Em meu programa está ocorrendo a seguinte exceção
21/03/2009 16:34:32 org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 1364, SQLState: HY000
21/03/2009 16:34:32 org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: Field 'citations_id' doesn't have a default value
21/03/2009 16:34:32 org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: could not insert collection: [br.ufrj.cos.bri.model.Documento.references#5]
	at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
	at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1205)
	at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:58)
	at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
	at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
	at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
	at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
	at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
	at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
	at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
	at br.ufrj.cos.bri.controller.CarregaXMLBanco.main(CarregaXMLBanco.java:206)
Caused by: java.sql.BatchUpdateException: Field 'citations_id' doesn't have a default value
	at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1257)
	at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:943)
	at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
	at org.hibernate.jdbc.BatchingBatcher.addToBatch(BatchingBatcher.java:56)
	at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1168)
	... 11 more
javax.persistence.RollbackException: Error while commiting the transaction
	at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)
	at br.ufrj.cos.bri.controller.CarregaXMLBanco.main(CarregaXMLBanco.java:206)
Caused by: org.hibernate.exception.GenericJDBCException: could not insert collection: [br.ufrj.cos.bri.model.Documento.references#5]
	at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
	at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1205)
	at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:58)
	at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
	at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
	at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
	at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
	at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
	at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
	at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
	... 1 more
Caused by: java.sql.BatchUpdateException: Field 'citations_id' doesn't have a default value
	at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1257)
	at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:943)
	at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
	at org.hibernate.jdbc.BatchingBatcher.addToBatch(BatchingBatcher.java:56)
	at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1168)
	... 11 more

Não sei se o problema se deve ao fato de na entidade principal possuir duas coleções de um mesmo tipo de objeto (Reference e Citation).
Em algumas situações, um destes objetos pode estar nulo (no caso em que ocorreu este erro o List que continha o objeto Citation estava nulo).

O que pode estar acontecendo? Segue o código da entidade principal
package br.ufrj.cos.bri.model;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

@Entity
public class Documento implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private long id;
	private String numeroPaper;
	private String numeroRegistro;
	private String numeroMedline;
	private String titulo;
	private String fonte;
	private String textoAbstract;
	private Map<String, Author> autores; 
	private List<Subtopic> majorSubtopic;
	//private List<Subtopic> minorSubtopic;
	private List<Cite> references;
	private List<Cite> citations;
	private String textoCompleto;
	private String tituloAbstract;
	
	@Id @GeneratedValue
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getNumeroPaper() {
		return numeroPaper;
	}
	public void setNumeroPaper(String numeroPaper) {
		this.numeroPaper = numeroPaper;
	}
	public String getNumeroRegistro() {
		return numeroRegistro;
	}
	public void setNumeroRegistro(String numeroRegistro) {
		this.numeroRegistro = numeroRegistro;
	}
	public String getNumeroMedline() {
		return numeroMedline;
	}
	public void setNumeroMedline(String numeroMedline) {
		this.numeroMedline = numeroMedline;
	}
	public String getTitulo() {
		return titulo;
	}
	public void setTitulo(String titulo) {
		this.titulo = titulo;
	}
	public String getFonte() {
		return fonte;
	}
	public void setFonte(String fonte) {
		this.fonte = fonte;
	}
	@Lob
	public String getTextoAbstract() {
		return textoAbstract;
	}
	public void setTextoAbstract(String textoAbstract) {
		this.textoAbstract = textoAbstract;
	}
	
	@ManyToMany
	public Map<String, Author> getAutores() {
		return autores;
	}
	public void setAutores(Map<String, Author> autores) {
		this.autores = autores;
	}
	@OneToMany
	public List<Subtopic> getMajorSubtopic() {
		return majorSubtopic;
	}
	public void setMajorSubtopic(List<Subtopic> majorSubtopic) {
		this.majorSubtopic = majorSubtopic;
	}
	/*
	@OneToMany
	public List<Subtopic> getMinorSubtopic() {
		return minorSubtopic;
	}
	public void setMinorSubtopic(List<Subtopic> minorSubtopic) {
		this.minorSubtopic = minorSubtopic;
	}*/
	
	@OneToMany
	public List<Cite> getReferences() {
		return references;
	}
	public void setReferences(List<Cite> references) {
		this.references = references;
	}
	
	@OneToMany
	public List<Cite> getCitations() {
		return citations;
	}
	public void setCitations(List<Cite> citations) {
		this.citations = citations;
	}
	@Lob
	public String getTextoCompleto() {
		return textoCompleto;
	}
	public void setTextoCompleto(String textoCompleto) {
		this.textoCompleto = textoCompleto;
	}
	@Lob
	public String getTituloAbstract() {
		return tituloAbstract;
	}
	public void setTituloAbstract(String tituloAbstract) {
		this.tituloAbstract = tituloAbstract;
	}
}
e da classe que faz a persistencia dos dados
package br.ufrj.cos.bri.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.apache.commons.collections.map.HashedMap;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import br.ufrj.cos.bri.model.Author;
import br.ufrj.cos.bri.model.Cite;
import br.ufrj.cos.bri.model.Documento;
import br.ufrj.cos.bri.model.Subtopic;


public class CarregaXMLBanco {
	public static void main(String[] args) {
		try {
			EntityManagerFactory emf = Persistence.createEntityManagerFactory("CarregaXMLBancoDados");
			EntityManager em = emf.createEntityManager();
			EntityTransaction tx = em.getTransaction();
			//tx.begin();
			
			File file = new File("cf74.xml");
			
			SAXBuilder sb = new SAXBuilder(true);
			Document d = sb.build(file);
			Element root = (Element) d.getRootElement();
			List children = root.getChildren();
			
			Iterator it = children.iterator();
			
			List<Documento> listDocuments = new ArrayList<Documento>();
			
			while (it.hasNext()) {
				StringBuilder stringBuilderTitleAbstract = new StringBuilder();
				StringBuilder stringBuilderFullText = new StringBuilder();
				
				Element e = (Element) it.next();
				
				Documento documentModel = new Documento();
				
				documentModel.setNumeroPaper(e.getChildText("PAPERNUM"));
				
				String title = e.getChildText("TITLE");
				documentModel.setTitulo(title);
				String conteudoAbstractExtract = e.getChildText("ABSTRACT");
				if (conteudoAbstractExtract != null) {
					documentModel.setTextoAbstract(conteudoAbstractExtract);
				} else {
					conteudoAbstractExtract = e.getChildText("EXTRACT");
					documentModel.setTextoAbstract(conteudoAbstractExtract);
				}
				stringBuilderTitleAbstract.append(title + " " + conteudoAbstractExtract);
				documentModel.setTituloAbstract(stringBuilderTitleAbstract.toString());
				
				documentModel.setNumeroMedline(e.getChildText("MEDLINENUM"));
				documentModel.setNumeroRegistro(e.getChildText("RECORDNUM"));
				
				documentModel.setFonte(e.getChildText("SOURCE"));
				
				
				Element elementAuthors = e.getChild("AUTHORS");
				if (elementAuthors != null) {
					Map<String, Author> autores = new HashedMap();
					
					List list = elementAuthors.getChildren();
					Iterator iterator = list.iterator();
					
					while (iterator.hasNext()) {
						Element a = (Element) iterator.next();
						String nameAuthor = a.getText();
						Author author = new Author();
						author.setName(nameAuthor);
						tx.begin();
						em.persist(author);
						tx.commit();
						autores.put(nameAuthor, author);
					}
					documentModel.setAutores(autores);
				}
				
				
				
				Element elementMajorSubj = e.getChild("MAJORSUBJ");
				if (elementMajorSubj != null) {
					List<Subtopic> listMajorSubj = new ArrayList<Subtopic>();
					
					List list = elementMajorSubj.getChildren();
					Iterator iterator = list.iterator();
					
					while (iterator.hasNext()) {
						Element a = (Element) iterator.next();
						String majorSubj = a.getText();
						Subtopic topic = new Subtopic();
						tx.begin();
						topic.setTopic(majorSubj);
						em.persist(topic);
						tx.commit();
						listMajorSubj.add(topic);
					}
					documentModel.setMajorSubtopic(listMajorSubj);
				} 
				
				/*
				Element elementMinorSubj = e.getChild("MINORSUBJ");
				if (elementMinorSubj != null) {
					List<Subtopic> listMinorSubj = new ArrayList<Subtopic>();
					
					List list = elementMinorSubj.getChildren();
					Iterator iterator = list.iterator();
					
					while (iterator.hasNext()) {
						Element a = (Element) iterator.next();
						String minorSubj = a.getText();
						Subtopic topic = new Subtopic();
						tx.begin();
						topic.setTopic(minorSubj);
						em.persist(topic);
						tx.commit();
						listMinorSubj.add(topic);
						
					}
					documentModel.setMinorSubtopic(listMinorSubj);
				} */
				
				
				
				Element elementReferences = e.getChild("REFERENCES");
				if (elementReferences != null) {
					List<Cite> listRefences = new ArrayList<Cite>();
					
					List list = elementReferences.getChildren();
					Iterator iterator = list.iterator();
					
					while (iterator.hasNext()) {
						Element a = (Element) iterator.next();
						Cite cite = new Cite();
						
						String num = a.getAttribute("num").getValue();
						String author = a.getAttribute("author").getValue();
						String publication = a.getAttribute("publication").getValue();
						String d1 = a.getAttribute("d1").getValue();
						String d2 = a.getAttribute("d2").getValue();
						String d3 = a.getAttribute("d3").getValue();
						
						cite.setAuthor(author);
						cite.setD1(d1);
						cite.setD2(d2);
						cite.setD3(d3);
						cite.setNum(Integer.parseInt(num));
						cite.setPublication(publication);
						tx.begin();
						em.persist(cite);
						tx.commit();
						listRefences.add(cite);
					}
					documentModel.setReferences(listRefences);
				}
				
				
				
				Element elementCitations = e.getChild("CITATIONS");
				if (elementCitations != null) {
					List<Cite> listCitations = new ArrayList<Cite>();
					
					List list = elementCitations.getChildren();
					Iterator iterator = list.iterator();
					
					while (iterator.hasNext()) {
						Element a = (Element) iterator.next();
						Cite cite = new Cite();
						
						String num = a.getAttribute("num").getValue();
						String author = a.getAttribute("author").getValue();
						String publication = a.getAttribute("publication").getValue();
						String d1 = a.getAttribute("d1").getValue();
						String d2 = a.getAttribute("d2").getValue();
						String d3 = a.getAttribute("d3").getValue();
						
						cite.setAuthor(author);
						cite.setD1(d1);
						cite.setD2(d2);
						cite.setD3(d3);
						cite.setNum(Integer.parseInt(num));
						cite.setPublication(publication);
						tx.begin();
						em.persist(cite);
						tx.commit();
						listCitations.add(cite);
					}
					documentModel.setCitations(listCitations);
				}
				
				tx.begin();
				em.persist(documentModel);
				tx.commit();
				listDocuments.add(documentModel);
			}
			System.out.println("Deu certo!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

abraço!

Criado 21 de março de 2009
Respostas 0
Participantes 1