我正在使用Eclipse,Xammp(tomcat和MySQL DB)和Hibernate。

我将创建类似relationship的东西。

我的实体类:

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...
         ...
}


我的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>


我的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>


我的主班:

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();


我的错误:

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


如果我在主类中不使用employee1.getColleagues().add(employee3);。然后一切正常,Hibernate将所有EMPLOYEE保存在MySQL数据库中。
只是employee1.getColleagues().add(employee3);´ dosn't work and i don't know why.I think it's because the hbm.xml`。但是我不知道,我必须改变什么

我数据库中的只是表EMPLOYEE

最佳答案

当将employee3添加到同事列表中时,看起来employee3是通过cascade={CascadeType.ALL})注释保存的。然后,当您调用session.save(employee3);时,它将再次保存,并且具有相同的ID,该ID使主键约束无效。因此,在将其添加到同事列表之前先保存它,或者在将其添加到同事列表后不要再次保存它。就像是:

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

09-13 05:19