Hibernate不传递生成的id

时间:2014-12-22 19:58:08

标签: hibernate hibernate-mapping

我遇到了使用hibernate进行映射的问题。 两个表矩阵和matrix_value。 enter image description here

CREATE TABLE matrix (
  matrix_id      INT AUTO_INCREMENT,
  number_of_rows INT NOT NULL DEFAULT 0,
  number_of_cols INT NOT NULL DEFAULT 0,
  PRIMARY KEY (matrix_id)
)  ENGINE =InnoDB;

CREATE TABLE matrix_value (
  id         INT AUTO_INCREMENT,
  matrix_id  INT NOT NULL DEFAULT 0,
  row_id     INT NOT NULL DEFAULT 0,
  column_id  INT NOT NULL DEFAULT 0,
  matrix_val INT NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  CONSTRAINT FK_matrix_value_matrix
  FOREIGN KEY (matrix_id) REFERENCES matrix (matrix_id)
    ON UPDATE CASCADE ON DELETE CASCADE
)  ENGINE =InnoDB;

生成matrix_values并插入矩阵行和列后 必须自动获取matrix_id并将其传递给matrix_values,但它会抛出

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'matrix_id' cannot be null
    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:526) 

它还添加到表格'矩阵'附加列< matrixValues'填空。

这是方法

 public void fillMatrixWithValues(MatrixValue[] values) throws Exception {        
    Session session = HibernateUtils.openSession();
    Transaction tx = null;
    try {
        tx = session.getTransaction();
        tx.begin();
        if (values != null && values.length != 0) {
            for (int i = 0; i < values.length; i++) {
                session.saveOrUpdate(values[i]);
            }
            tx.commit();
        }       
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        logger.error("Error fillMatrixWithValues-method: " + e.getMessage());
        throw e;
    }     finally {
        session.close();
    }
}

矩阵(POJO)

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "matrix_id", unique = true, nullable = false)
private int matrixId;

@Column(name = "number_of_rows", unique = false, nullable = false)
private int numberOfRows;

@Column(name = "number_of_cols", unique = false, nullable = false)
private int numberOfCols;

@OneToMany (mappedBy= "matrix", fetch = FetchType.EAGER)
@Transient
private List<MatrixValue> values;

MatrixValues(POJO)

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id", unique = true, nullable = false)
private int id;

@PrimaryKeyJoinColumn
@Column(name = "matrix_id", unique = false, nullable = false, insertable = false, updatable = false)
private int matrixId;

@Column(name = "row_id", unique = false, nullable = false)
private int rowId;

@Column(name = "column_id", unique = false, nullable = false)
private int columnId;

@Column(name = "matrix_val", unique = false, nullable = false)
private int value;

@ManyToOne
@JoinColumn(name = "matrix_id")
private Matrix matrix;

getters and setters

hibernate.xml

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/matrixbase</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">10</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.connection.autocommit">false</property>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.jdbc.batch_size">30</property>
        <property name="hibernate.jdbc.batch_versioned_data">true</property>
        <property name="hibernate.jdbc.use_get_generated_keys">true</property>

        <mapping class="kuidin.task5.entity.Matrix" />
        <mapping class="kuidin.task5.entity.MatrixValue" />
<hibernate-configuration>

有什么问题? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

删除MatrixValues类中的@Transient和matrix_id字段(带注释)。你也不需要。

说明:

  1. matrixValues集合不是瞬态的。它应该被持久化,虽然Matrix不是关联的“所有者”(当持久化Hibernate将查看映射字段以找到要存储的值时,虽然这应该产生相同的值),这称为“逆”端(双向)协会。
  2. matrixValues中的matrix_id列将填充分配给矩阵字段的矩阵的id。添加附加字段是多余的,并将其注释为@PrimaryKeyJoinColumn只是错误:该列不是包含它的表的主键的一部分。