2016-05-23 1 views
0

Ich benutze Eclipse, Xammp (Tomcat und MySQL DB) und Hibernate.Beziehung mit Hibernate

ich werde etwas wie relatifipt erstellen.

meine Entity-Klasse:

package Dto; 

import java.util.HashSet; 
import java.util.Set; 

import javax.persistence.CascadeType; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.JoinTable; 
import javax.persistence.ManyToMany; 
import javax.persistence.Table; 
import javax.persistence.JoinColumn; 

@Entity 
@Table(name="EMPLOYEE") 
public class Employee { 

    @Id 
    @Column(name="EMPLOYEE_ID") 
    @GeneratedValue 
    private Long employeeId; 

    @Column(name="FIRSTNAME") 
    private String firstname; 

    @Column(name="LASTNAME") 
    private String lastname; 


    @ManyToMany(cascade={CascadeType.ALL}) 
    @JoinTable(name="EMPLOYEE_COLLEAGUE", 
     joinColumns={@JoinColumn(name="EMPLOYEE_ID")}, 
     inverseJoinColumns={@JoinColumn(name="COLLEAGUE_ID")}) 
    private Set<Employee> colleagues = new HashSet<Employee>(); 

    @ManyToMany(mappedBy="colleagues") 
    private Set<Employee> teammates = new HashSet<Employee>(); 

    public Employee() { 
    } 

    public Employee(String firstname, String lastname) { 
     this.firstname = firstname; 
     this.lastname = lastname; 
    } 

    //Getter and Setter... 
     ... 
} 

Mein hbm.xml:

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<!-- Generated 23.05.2016 15:44:11 by Hibernate Tools 3.5.0.Final --> 
<hibernate-mapping> 
    <class name="Dto.Employee" table="EMPLOYEE"> 
     <id name="employeeId" type="java.lang.Long"> 
      <column name="EMPLOYEEID" /> 
      <generator class="native" /> 
     </id> 
     <property name="firstname" type="java.lang.String"> 
      <column name="FIRSTNAME" /> 
     </property> 
     <property name="lastname" type="java.lang.String"> 
      <column name="LASTNAME" /> 
     </property> 
     <set name="colleagues" table="EMPLOYEE" inverse="false" lazy="true"> 
      <key> 
       <column name="EMPLOYEEID" /> 
      </key> 
      <one-to-many class="Dto.Employee" /> 
     </set> 
     <set name="teammates" table="EMPLOYEE" inverse="false" lazy="true"> 
      <key> 
       <column name="EMPLOYEEID" /> 
      </key> 
      <one-to-many class="Dto.Employee" /> 
     </set> 
    </class> 
</hibernate-mapping> 

Mein hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
    <session-factory> 
     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
     <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Hibernate</property> 
     <property name="hibernate.connection.username">root</property> 
     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
     <property name="hbm2ddl.auto">create-drop</property> 

     <mapping resource="Dto/Employee.hbm.xml" /> 
    </session-factory> 
</hibernate-configuration> 

Meine Hauptklasse:

Configuration configuration = new Configuration(); 
     configuration.configure("resources/hibernate.cfg.xml"); 

     SessionFactory sessionFactory = configuration.buildSessionFactory(); 

     Session session = sessionFactory.openSession(); 

     session.beginTransaction(); 



      Employee employee1 = new Employee("Sergey", "Brin"); 
      Employee employee2 = new Employee("Larry", "Page"); 
      Employee employee3 = new Employee("Marrisa", "Mayer"); 
      Employee employee4 = new Employee("Matt", "Cutts"); 

      employee1.getColleagues().add(employee3); 
//   employee1.getColleagues().add(employee4); 


      session.save(employee1); 
      session.save(employee2); 
      session.save(employee3); 
      session.save(employee4); 

      session.getTransaction().commit(); 
      session.close(); 

Mein Fehler:

log4j:WARN No appenders could be found for logger (org.jboss.logging). 
log4j:WARN Please initialize the log4j system properly. 
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement 
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59) 
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) 
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) 
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97) 
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207) 
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45) 
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1313) 
    at org.hibernate.persister.collection.OneToManyPersister.recreate(OneToManyPersister.java:170) 
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50) 
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560) 
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434) 
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337) 
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) 
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295) 
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468) 
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135) 
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352) 
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485) 
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147) 
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38) 
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231) 
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65) 
    at Dao.UserDao.testFriend(UserDao.java:208) 
    at Test.Main.main(Main.java:40) 
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY' 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
    at java.lang.reflect.Constructor.newInstance(Unknown Source) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) 
    at com.mysql.jdbc.Util.getInstance(Util.java:387) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:932) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551) 
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) 
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073) 
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009) 
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5094) 
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994) 
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204) 
    ... 19 more 

wenn ich leider keinen Gebrauch employee1.getColleagues().add(employee3); in meinem Mainclass. Dann funktioniert alles und Hibernate speichert alle EMPLOYEE in der MySQL-Datenbank. nur die employee1.getColleagues().add(employee3);´ dosn't work and i don't know why. I think it's because the hbm.xml`. Aber ich weiß nicht, was ich ändern muss

in meiner Datenbank ist nur die Tabelle EMPLOYEE.

+0

Sie verwenden Anmerkungen und XML-Konfiguration. Sie sollten entweder das eine oder das andere verwenden, nie beide –

Antwort

0

Es scheint, dass employee3 über die cascade={CascadeType.ALL}) Annotation gespeichert wird, wenn employee3 zur Kollegenliste hinzugefügt wird. Dann wird es erneut gespeichert, wenn Sie session.save(employee3); aufrufen, und es hat dieselbe ID, die die Primärschlüsseleinschränkung ungültig macht. Speichern Sie es also entweder zuerst, bevor Sie es der Kollegenliste hinzufügen, oder speichern Sie es nicht erneut, nachdem Sie es zur Liste hinzugefügt haben. Etwas wie:

employee3 = session.save(employee3); 
employee1.getColleagues().add(employee3); 
+0

Ich änderte den Code und legte die ID manuell. Und es funktioniert auch nicht. –

+0

und wenn ich zuerst speichern und dann zu Kollegen hinzufügen. Es ist der gleiche Fehler, auch –

+0

Es ist seltsam, dass Sie beide Anmerkungen und hibernate.xml haben. Bist du sicher, dass du das kannst? [In Hibernate: Ist es möglich, Anmerkungen und XML-Konfiguration für eine Entität zu mischen?] (Http://stackoverflow.com/questions/8643166/in-hibernate-is-it-possible-to-mix-annotations-and-xml -configuration-for-a-ent) –

Verwandte Themen