0
votes

I am newbie in hibernate. I've looked some tutorials but what I can't find this issue :

  • How can I add a new line into one table that have one dependency with another one that already exists ?

hibernate.cfg.xml

>     <?xml version='1.0' encoding='utf-8'?>
>     <!DOCTYPE hibernate-configuration PUBLIC
>          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
>         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
>     
>     <hibernate-configuration>
>       <session-factory>
>           <!-- Paramètres de connexion à la base de données -->
>           <!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property> -->
>           <!-- <property name="connection.url">jdbc:mysql://localhost:3306/bh</property> -->
>           <!-- <property name="connection.username">root</property> -->
>           <!-- <property name="connection.password"></property> -->
>           <!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
>     
>           <property name="connection.driver_class">org.postgresql.Driver</property>
>           <property name="connection.url">jdbc:postgresql://localhost:5432/projetForum</property>
>           <property name="connection.username">postgres</property>
>           <property name="connection.password">esct</property>
>           <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
>     
>           <!-- Comportement pour la conservation des tables -->
>           <property name="hbm2ddl.auto">update</property>
>     
>           <!-- Activation : affichage en console, commentées et formatées -->
>           <property name="show_sql">true</property>
>           <property name="hibernate.format_sql">true</property>
>           <property name="use_sql_comments">true</property>
>     
>           <!-- Fichiers à mapper -->
>           <mapping class="com.forum.beans.Utilisateur" />
>           <mapping class="com.forum.beans.Topic" />
>           <mapping class="com.forum.beans.Post" />
>           
>       </session-factory>
>     </hibernate-configuration>

my beans classes

package com.forum.beans;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlTransient;

import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

@Entity
@Table(name = "utilisateur")
public class Utilisateur {

  @Id
  @Column(name = "utilisateur_email")
  private String email;
  @Column(name = "utilisateur_mdp")
  private String motDePasse;
  @Column(name = "utilisateur_nom")
  private String nom;
  @Column(name = "utilisateur_avatar")
  private String avatar;
  @Column(name = "utilisateur_localisation")
  private String localisation;
  @Column(name = "utilisateur_siteweb")
  private String siteweb;
  @Column(name = "utilisateur_dateInscrit")
  private String dateInscrit;
  @Column(name = "utilisateur_dateDernVisite")
  private String dateDernVisite;
  @Column(name = "utilisateur_description")
  private String description;
  @Column(name = "utilisateur_dateNaiss")
  private String dateDeNaissance;

  @OneToMany(mappedBy = "tcreateur")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Topic> topicList;

  @OneToMany(mappedBy = "pcreateur")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Post> postList;

  public Utilisateur(String email, String motDePasse, String nom,
          String localisation, String siteweb, String description) {
      this.email = email;
      this.motDePasse = motDePasse;
      this.nom = nom;
      this.topicList = null;
      this.postList = null;
      this.siteweb = siteweb;
      this.description = description;
      this.localisation = localisation;

      SimpleDateFormat formater = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
      Date aujourdhui = new Date();
      this.dateDernVisite = formater.format(aujourdhui);
  }

  public Utilisateur() {
  }

  public String getDateDernVisite() {
      return dateDernVisite;
  }

  public void setDateDernVisite(String dateDernVisite) {
      this.dateDernVisite = dateDernVisite;
  }

  public String getDateDeNaissance() {
      return dateDeNaissance;
  }

  public void setDateDeNaissance(String dateDeNaissance) {
      this.dateDeNaissance = dateDeNaissance;
  }

  public String getDescription() {
      return description;
  }

  public void setDescription(String description) {
      this.description = description;
  }

  public String getAvatar() {
      return avatar;
  }

  public void setAvatar(String avatar) {
      this.avatar = avatar;
  }

  public String getLocalisation() {
      return localisation;
  }

  public void setLocalisation(String localisation) {
      this.localisation = localisation;
  }

  public String getSiteweb() {
      return siteweb;
  }

  public void setSiteweb(String siteweb) {
      this.siteweb = siteweb;
  }

  public String getDateInscrit() {
      return dateInscrit;
  }

  public void setDateInscrit(String dateInscrit) {
      this.dateInscrit = dateInscrit;
  }

  public String getdateDernVisite() {
      return dateDernVisite;
  }

  public void setdateDernVisite(String dateDernVisite) {
      this.dateDernVisite = dateDernVisite;
  }

  @XmlTransient
  public List<Post> getPostList() {
      return postList;
  }

  public void setPostList(List<Post> postList) {
      this.postList = postList;
  }

  @XmlTransient
  public List<Topic> getTopicList() {
      return topicList;
  }

  public void setTopicList(List<Topic> topicList) {
      this.topicList = topicList;
  }

  public void setEmail(String email) {
      this.email = email;
  }

  public String getEmail() {
      return email;
  }

  public void setMotDePasse(String motDePasse) {
      this.motDePasse = motDePasse;
  }

  public String getMotDePasse() {
      return motDePasse;
  }

  public void setNom(String nom) {
      this.nom = nom;
  }

  public String getNom() {
      return nom;
  }
}

And the class that i'm trying to add :

>      package com.forum.beans;
>     
>     import java.text.SimpleDateFormat;
>     import java.util.Date;
>     import java.util.List;
>     
>     import javax.persistence.CascadeType;
>     import javax.persistence.Column;
>     import javax.persistence.Entity;
>     import javax.persistence.GeneratedValue;
>     import javax.persistence.GenerationType;
>     import javax.persistence.Id;
>     import javax.persistence.JoinColumn;
>     import javax.persistence.ManyToOne;
>     import javax.persistence.OneToMany;
>     import javax.persistence.Table;
>     import javax.xml.bind.annotation.XmlTransient;
>     
>     import org.hibernate.annotations.LazyCollection;
>     import org.hibernate.annotations.LazyCollectionOption;
>     
>     @Entity
>     @Table(name = "topic")
>     public class Topic {
>     
>       @Id
>       @Column(name = "topic_id")
>       @GeneratedValue(strategy = GenerationType.AUTO)
>       private Integer id;
>       @Column(name = "topic_titre")
>       private String titre;
>       @Column(name = "topic_corps")
>       private String corps;
>       @Column(name = "topic_date")
>       private String date;
>     
>       @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
>       @JoinColumn(name = "topic_createur")
>       private Utilisateur tcreateur;
>     
>       @OneToMany(mappedBy = "ptopic")
>       @LazyCollection(LazyCollectionOption.FALSE)
>       private List<Post> tpostList;
>     
>       public Topic(String titre, String corps) {
>           this.titre = titre;
>           this.corps = corps;
>     
>           SimpleDateFormat formater = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
>           Date aujourdhui = new Date();
>           this.date = formater.format(aujourdhui);
>     
>       }
>     
>       public Topic() {
>       }
>     
>       @XmlTransient
>       public List<Post> getTpostList() {
>           return tpostList;
>       }
>     
>       public void setTpostList(List<Post> tpostList) {
>           this.tpostList = tpostList;
>       }
>     
>       @XmlTransient
>       public List<Post> getPostList_topic() {
>           return tpostList;
>       }
>     
>       public void setPostList_topic(List<Post> tpostList) {
>           this.tpostList = tpostList;
>       }
>     
>       public void setDate(String date) {
>           this.date = date;
>       }
>     
>       public void setTcreateur(Utilisateur tcreateur) {
>           this.tcreateur = tcreateur;
>       }
>     
>       public String getDate() {
>           return date;
>       }
>     
>       public void setDateDernModif(String date) {
>           this.date = date;
>       }
>     
>       public Utilisateur getTcreateur() {
>           return tcreateur;
>       }
>     
>       public void setEditeur(Utilisateur tcreateur) {
>           this.tcreateur = tcreateur;
>       }
>     
>       public Integer getId() {
>           return id;
>       }
>     
>       public void setId(Integer id) {
>           this.id = id;
>       }
>     
>       public String getTitre() {
>           return titre;
>       }
>     
>       public void setTitre(String titre) {
>           this.titre = titre;
>       }
>     
>       public String getCorps() {
>           return corps;
>       }
>     
>       public void setCorps(String corps) {
>           this.corps = corps;
>       }
>     }

Part of my main class:

>     Utilisateur utilisateur = (Utilisateur) session
>                   .getAttribute("utilisateur");
>     
>           TopicDAO<com.forum.beans.Topic, Integer> ts = new TopicDAO<com.forum.beans.Topic, Integer>();
>           TopicForm form = new TopicForm();
>           com.forum.beans.Topic t = form.creerSujet(request);
>           List<com.forum.beans.Topic> tl =utilisateur.getTopicList();
>     
>           try {
>               if (utilisateur.getTopicList() == null)
>                   tl = (List<com.forum.beans.Topic>) new ArrayList<com.forum.beans.Topic>();
>               else
>                   tl = utilisateur.getTopicList();
>           } catch (Exception e) {
>               System.out.println(e);
>           }
>     
>               tl.add(t);
>               t.setTcreateur(utilisateur);
>               utilisateur.setTopicList(tl);
>               ts.create(t);

So, my problem is that I make my Topic class a persisting one, but I get a JDBC exception saying that Utilisateur class already exists in my DB

The full stacktrace

22:44:48,476 WARN JDBCExceptionReporter:100 - SQL Error: 0, SQLState: 23505 22:44:48,477 ERROR JDBCExceptionReporter:101 - L'élément du batch 0 /* insert com.forum.beans.Utilisateur */ insert into utilisateur (utilisateur_avatar, utilisateur_dateNaiss, utilisateur_dateDernVisite, utilisateur_dateInscrit, utilisateur_description, utilisateur_localisation, utilisateur_mdp, utilisateur_nom, utilisateur_siteweb, utilisateur_email) values (NULL, NULL, '16-08-2013 10:44:42', '16-08-2013 10:04:04', NULL, NULL, 'mee', 'testerMan', NULL, '[email protected]') a été annulé. Appeler getNextException pour en connaître la cause. 22:44:48,477 WARN JDBCExceptionReporter:100 - SQL Error: 0, SQLState: 23505 22:44:48,478 ERROR JDBCExceptionReporter:101 - ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « utilisateur_pkey » Détail : La clé « (utilisateur_email)=([email protected]) » existe déjà. 22:44:48,482 ERROR AbstractFlushingEventListener:324 - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114) at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109) at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2242) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) 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:167) 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:1028) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at com.forum.dao.TopicDAO.create(TopicDAO.java:23) at com.forum.servlets.Nouveau.doPost(Nouveau.java:55) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.BatchUpdateException: L'élément du batch 0 /* insert com.forum.beans.Utilisateur */ insert into utilisateur (utilisateur_avatar, utilisateur_dateNaiss, utilisateur_dateDernVisite, utilisateur_dateInscrit, utilisateur_description, utilisateur_localisation, utilisateur_mdp, utilisateur_nom, utilisateur_siteweb, utilisateur_email) values (NULL, NULL, '16-08-2013 10:44:42', '16-08-2013 10:04:04', NULL, NULL, 'mee', 'testerMan', NULL, '[email protected]') a été annulé. Appeler getNextException pour en connaître la cause. at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2746) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1887) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2893) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ... 34 more org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

1
Post the exact and complete stack trace of the exception, instead of posting your interpretation of the error message. And explain the relationship between your question and the code. What is this entity that already exists? - JB Nizet
@JBNizet, I've updated my post - Lucie Leigh Allen
How is the utilisateur variable initialized? - JB Nizet
@JBNizet, I've just updated my post about that ^^ - Lucie Leigh Allen

1 Answers

0
votes

In your main class code, I anyway see a potential NullPointer when you are getting the list as it is null by default. You will have to create a new list and assign to it.

com.forum.beans.Topic t = form.creerSujet(request);
List<com.forum.beans.Topic> tl =new ArrayList<com.forum.beans.Topic>();
tl.add(t);
utilisateur.setTopicList(tl);
t.setTcreateur(utilisateur);
ts.create(t);

And please post the full exception stack trace.