如何在Hibernate中从XML生成主键?

时间:2016-08-05 08:11:13

标签: java xml hibernate

我有一个用户类:

public class User{
    private Long userId;
}

我在xml中使用它:

<id name="userId" type="long" unsaved-value="null">
        <column name="USER_ID" not-null="true" />
        <generator class="native" />
</id>

但是当我尝试保存用户对象而不将userId分配给对象时,我收到以下错误:

Caused by: java.sql.SQLException: Field 'USER_ID' doesn't have a default value
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
    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:208)
    ... 22 more

我希望Hibernate为我生成id。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

您需要为USER_ID列设置autoincrement

ALTER TABLE users ADD USER_ID INT UNSIGNED NOT NULL AUTO_INCREMENT;

native指令意味着您的数据库负责生成ID。因为你没有设置策略来在数据库端生成id,所以你得到异常java.sql.SQLException: Field 'USER_ID' doesn't have a default value