hibernatexml中javaMap Package 的自动生成主键

iswrvxsc  于 2021-06-23  发布在  Mysql
关注(0)|答案(0)|浏览(378)

我试图用Hibernate5.0将以下对象Map到数据库表。

class Ticket {

  private TicketId ticketId;
  private String description;

  private Ticket() {}
  private Ticket(final String description) {
    this.description = description;
  }
  public TicketId ticketId() { return ticketId; }
  public String description() { return description; }
  // equals and hashCode
}

哪里 TicketId 是一个非常简单的 Package 主键,需要在数据库中自动生成:

class TicketId implements Serializable {

  private Long id;

  private TicketId() {}
  public Long id() { return id; }
  // equals and hashCode
}

mysql数据库表架构如下:

CREATE TABLE `TICKETS` (
  `ID` INT(11) unsigned NOT NULL AUTO_INCREMENT,
  `DESCRIPTION` VARCHAR(255),
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB;

我已经阅读了vlad michalcea的文章,但是我想使用xml,我提出了以下Map:

<?xml version="1.0"?>
<hibernate-mapping default-access="field" default-cascade="all"
  xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
  <class name="some.package.Ticket" table="TICKETS" lazy="true">
    <composite-id name="ticketId">
      <key-property name="id" column="ID" type="java.lang.Long"/>
    </composite-id>
    <property name="description" column="DESCRIPTION" type="java.lang.String"/>
    <sql-insert>INSERT INTO TICKETS (DESCRIPTION) VALUES (?)</sql-insert>
  </class>
</hibernate-mapping>

但是,当我尝试持久化新的代码时,orm代码失败了 Ticket . 下面的代码生成 org.hibernate.id.IdentifierGenerationException: null id generated for:class some.package.Ticket ```
try (final Session session = sessionFactory.openSession()) {
final Ticket ticket = new Ticket("description");
session.save(ticket);
}

有办法解决这个问题吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题