public class MySequenceGenerator implements IdentifierGenerator {
public static final String QUERY_NAME = "MySequence.newId";
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
Long id = null;
Connection connection = session.connection();
try {
PreparedStatement preparedStatement = connection.prepareStatement(session
.getNamedQuery(QUERY_NAME).getQueryString());
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
id = resultSet.getLong(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return id;
}
}
hbm.xml
...
<sql-query name="MySequence.newId">
<return-scalar column="id" type="long" />
<![CDATA[
select
seq_my.NEXTVAL id
from
dual
]]>
</sql-query>
...
ru.olimpiks.MyEntity.java
@Entity
@Table(name = "MY_TABLE")
public class MyEntity implements java.io.Serializable {
private Long id;
@Id
@Column(name = "ID")
@GeneratedValue(generator = "my_id")
@GenericGenerator(name = "my_id", strategy = "ru.olimpiks.MySequenceGenerator")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
// ...
}

0 comments:
Отправить комментарий