更新映射为@ManyToMany,@ JoinTable和@OrderColumn(具有唯一约束)的实体列表时,MySQLIntegrityConstraintViolationException

时间:2012-03-16 12:54:28

标签: java mysql jpa eclipselink unique-constraint

PrequalificationCompany个实体(Partnership)之间存在多对多关系。这三个表的DDL是:

CREATE TABLE Prequalifications
(
  id              INTEGER      NOT NULL IDENTITY,
  user_id         INTEGER      NOT NULL,
  name            VARCHAR(100) NOT NULL,

  PRIMARY KEY (id),
  FOREIGN KEY (user_id) REFERENCES Users (id)
);

CREATE TABLE Partnerships
(
  prequalification_id INTEGER            NOT NULL,
  company_id          INTEGER            NOT NULL,
  ordinal_nbr         SMALLINT DEFAULT 0 NOT NULL,

  PRIMARY KEY (prequalification_id, company_id),
  FOREIGN KEY (prequalification_id) REFERENCES Prequalifications (id),
  FOREIGN KEY (company_id) REFERENCES Companies (id),
  UNIQUE (prequalification_id, ordinal_nbr)
);

CREATE TABLE Companies
(
  id       INTEGER     NOT NULL,
  dnd_type VARCHAR(10) NOT NULL,

  PRIMARY KEY (id),
  FOREIGN KEY (id) REFERENCES Organizations (id) -- just an inherited ID, never mind!
);

请注意Partnerships的PQ ID和序号上的唯一约束:每个PQ只能有一个公司的位置。

这已在Prequalification中映射为@ManyToMany + @JoinTable,其中包含@OrderColumn每个PQ公司的订单(Partnerships的订单列为ordinal_nbr):

@Entity
@Table(name = "Prequalifications")
public class Prequalification implements Serializable
{
    ...

    @ManyToMany
    @JoinTable(name = "Partnerships", joinColumns = @JoinColumn(name = "prequalification_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "company_id", referencedColumnName = "id"))
    @OrderColumn(name = "ordinal_nbr", nullable = false)
    private List<Company> companies;

    ...
}

这是从GUI调用的更新方法。请注意,GUI上的列表仅包括外部公司,内部公司(应该是)始终在索引为零:

@ManagedBean
@ViewScoped
public class PqHome implements DropListener, Serializable
{
    ...

    private Prequalification pq;
    private Integer userId;
    private List<Company> participatingCompanies; // xetters omitted!

    ...

    public void update()
    {
        // assign new owner
        pq.setUser(userService.findSingleUser(userId));

        Company internal = companyManager.getInternalCompany();

        // find internal company
        int index = participatingCompanies.indexOf(internal);

        // if internal company missing or at non-zero index: we need to repair this
        if ( index != 0 )
        {
            // if internal exists at some wrong place, remove it
            if ( index > 0 )
            {
                participatingCompanies.remove(index);
            }

            // (re-)add at index zero
            participatingCompanies.add(0, internal);
        }       

        pq.setCompanies(participatingCompanies);

        // update and get *new* merged instance
        pq = pqService.update(pq);

        participatingCompanies = null;
        init(); // some not so important (re-)initialization...
    }

    ...
}

在客户端JSF页面中,使用字段participatingCompanies,如:

<rich:pickList value="#{pqHome.participatingCompanies}"
               var="company"
               converter="#{companyConverter}"
               orderable="true"
               sourceCaption="Available companies"
               targetCaption="Selected companies">
  <f:selectItems value="#{companyManager.externalCompanies}" />
  <rich:column>#{company.name}</rich:column>
</rich:pickList>

不要被吓倒的RichFaces组件。引用#{pqHome.participatingCompanies}的列表只包含可选(外部)公司。

screenshot

当我点击更新按钮(未显示)时,调用update bean上的PqHome方法。使用EclipseLink 2.3.2 在 GlassFish 3.1.2上执行代码时,会抛出以下异常:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2-2' for key 'partnerships_multi_uq'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
    at com.mysql.jdbc.jdbc2.optional.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:875)
    at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
    ... 128 more

此异常在日志中重复多次。其他PQ具有相同的问题,仅涉及其他独特的列组合,例如, '1-1'。可以在此处找到服务器日志:http://www.eclipse.org/forums/index.php/t/310923/

更新代码有什么问题?它在Hibernate上没有问题。

1 个答案:

答案 0 :(得分:1)

EclipseLink更新连接表中的@OrderColumn以有效维护订单,因此您无法对其进行唯一约束。因此,删除或推迟唯一约束。

您可以在EclipseLink上记录一个错误,添加一个选项以避免此限制。