我正在尝试使用Hibernate 5.0将以下对象映射到数据库表中。
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
是一个非常简单的包装主键,需要在数据库中自动生成:
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;
我已经读过the article by Vlad Michalcea,但是我想使用xml并想出了以下映射:
<?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>
但是,当我尝试保留新的Ticket
时,ORM代码失败。
以下代码产生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);
}
有没有办法解决这个问题?