# Hibernate oneToMany Syntaxfehler



## DirtyBit (20. Jul 2019)

Hallo,
ich arbeite mich gerade in die oneToMany relation bei Hibernate ein. Ich erstelle Objekte vom Typ "Project" ein Project kann bei mir beliebig viele "Reports" haben. Die Dazugehörige Tabelle für die Assoziation wird von Hibernate Korrekt angelegt und beim ersten hinzufügen einer "Reports" klappt auch alles. Wenn ich allerdings einem "Project" einen weiteren "Report" hinzufügen möchte kriege ich einen Fehler:



Spoiler: Project.java mapping





```
@Entity
@Table(name = "TB_PROJECT")
public class Project implements Serializable {

  private static final long serialVersionUID = 1L;
 
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  @Column(name ="PROJECT_ID", unique = true, nullable = false)
  private int projectID;
 
  @Column(name = "NAME", unique = false, nullable = false)
  private String name;
 
  @Column(name = "CLIENT", unique = false, nullable = false)
  private String client;

  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinTable(name="PROJECT_REPORTS", joinColumns= {@JoinColumn(name="PROJECT_ID", referencedColumnName="PROJECT_ID")}
      , inverseJoinColumns= {@JoinColumn(name="REPORT_ID", referencedColumnName="REPORT_ID")})
  private List<Report> reportList = new ArrayList<Report>();
```






Spoiler: Report.java mapping





```
@Entity
@Table(name = "TB_REPORT", uniqueConstraints = {
        @UniqueConstraint(columnNames = "REPORT_ID") })
public class Report implements Serializable{
    
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name ="REPORT_ID", unique = true, nullable = false)
    private int reportID;
    
    @Column(name = "NAME", unique = false, nullable = false)
    private String name;
    
    @Column(name ="AMOUNT_COMPONENTS")
    private int amountComponents;
    
    @Column(name ="AMOUT_ACCEPTED")
    private int amountAccepted;
    
    @Column(name = "AMOUNT_REJECTED")
    private int amountRejected;
    
    @Column(name = "AMOUNT_DRAFT")
    private int amountUnderDevelopment;
    
    @Column(name = "AMOUNT_REVIEW")
    private int amountUnderReview;
    
    @Column(name = "TODELETE")
    private Boolean toDelete = false;
```




Folgender Code wird ausgeführt um ein Projekt und seine Assoziation zu updaten:
*Das klappt auch beim ersten mal !*
Sobald ich aber ein zweites Element in die Liste einfügen will kommt der Fehler.


Spoiler: Hibernate





```
@Override
    public void updatePersistentProject(Project project) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.saveOrUpdate(project);
            session.getTransaction().commit();
            session.close();
        } catch (HibernateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
```






Spoiler: Console Output





```
...

Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into TB_REPORT (REPORT_ID, AMOUT_ACCEPTED, AMOUNT_COMPONENTS, AMOUNT_REJECTED, AMOUNT_DRAFT, AMOUNT_REVIEW, NAME, TODELETE) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update TB_PROJECT set CLIENT = ?, NAME = ?, TO_DELETE = ? where PROJECT_ID=?
Hibernate: update TB_REPORT set AMOUT_ACCEPTED = ?, AMOUNT_COMPONENTS = ?, AMOUNT_REJECTED = ?, AMOUNT_DRAFT = ?, AMOUNT_REVIEW = ?, NAME = ?, TODELETE = ? where REPORT_ID=?
Hibernate: update TB_REPORT set AMOUT_ACCEPTED = ?, AMOUNT_COMPONENTS = ?, AMOUNT_REJECTED = ?, AMOUNT_DRAFT = ?, AMOUNT_REVIEW = ?, NAME = ?, TODELETE = ? where REPORT_ID=?
Hibernate: delete PROJECT_REPORTS where PROJECT_ID=?

Juli 20, 2019 10:07:40 VORM. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42601
Juli 20, 2019 10:07:40 VORM. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: FEHLER: Syntaxfehler bei »PROJECT_REPORTS«
  Position: 8
Juli 20, 2019 10:07:40 VORM. org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]]
Juli 20, 2019 10:07:40 VORM. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [ReportServlet] in context with path [/project] threw exception
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1436)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:487)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2786)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:1932)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:456)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:272)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
    at dao.ProjectDAOImpl.updatePersistentProject(ProjectDAOImpl.java:70)
    at logic.ReportImpl.createReport(ReportImpl.java:39)
    at gui.ReportServlet.createReport(ReportServlet.java:223)
    at gui.ReportServlet.doGet(ReportServlet.java:64)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at gui.LoginFilter.doFilter(LoginFilter.java:77)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [delete PROJECT_REPORTS where PROJECT_ID=?]
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
    at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:77)
    at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:95)
    at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:125)
    at org.hibernate.metamodel.model.domain.internal.collection.JoinTableRemovalExecutor.execute(JoinTableRemovalExecutor.java:123)
    at org.hibernate.metamodel.model.domain.spi.AbstractPersistentCollectionDescriptor.remove(AbstractPersistentCollectionDescriptor.java:1245)
    at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:78)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:602)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:474)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:358)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1430)
    ... 39 more
Caused by: org.postgresql.util.PSQLException: FEHLER: Syntaxfehler bei »PROJECT_REPORTS«
  Position: 8
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2468)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2211)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:309)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
    at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:68)
    ... 49 more
```




Er sagt mir dass ein "SyntaxFehler" in der Assoziations Tabelle vorliegt ?

Danke für jede Hilfe!
LG DirtyBit


----------



## mihe7 (20. Jul 2019)

DirtyBit hat gesagt.:


> delete PROJECT_REPORTS where PROJECT_ID=?


Das muss IMO 

```
delete from ...
```
heißen. Wenn das Statement automatisch und ohne Dein Zutun in der Form von Hibernate erzeugt wird: hast Du evtl. einen falschen Dialekt eingestellt? Ansonsten, ggf. ein Bug.


----------



## DirtyBit (20. Jul 2019)

Tatsächlich führe ich nie so  ein Statement aus, es wird automatisch von Hibernate erzeugt und ich komme nicht drauf wieso. Schließlich tritt der Fehler erst beim einfügen des *zweiten *elements auf. Das erste wird problemlos erzeugt. Und bei zweiten mal wird genau der selbe Code ausgeführt , allerdings versucht hibernate dann irgendwas aus der Project_Reports tabelle zu löschen.


----------



## mihe7 (20. Jul 2019)

DirtyBit hat gesagt.:


> und ich komme nicht drauf wieso


Speicher mal zuerst den Report ab und füg ihn dann zum Projekt hinzu. Unabhängig davon ist das SQL-Statement falsch, daher:


mihe7 hat gesagt.:


> hast Du evtl. einen falschen Dialekt eingestellt? Ansonsten, ggf. ein Bug.


----------

