栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Hibernate中将字符串映射到数据库序列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Hibernate中将字符串映射到数据库序列

实现一个自定义的IdentifierGenerator类;从博客文章:

import java.io.Serializable;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import org.hibernate.HibernateException;import org.hibernate.engine.spi.SessionImplementor;import org.hibernate.id.IdentifierGenerator;public class StringKeyGenerator implements IdentifierGenerator {    @Override    public Serializable generate(SessionImplementor session, Object collection) throws HibernateException {        Connection connection = session.connection();        PreparedStatement ps = null;        String result = "";        try { // Oracle-specific pre to query a sequence ps = connection.prepareStatement("SELECt TABLE_SEQ.nextval AS TABLE_PK FROM dual"); ResultSet rs = ps.executeQuery(); if (rs.next()) {     int pk = rs.getInt("TABLE_PK");     // Convert to a String     result = Integer.toString(pk); }        } catch (SQLException e) { throw new HibernateException("Unable to generate Primary Key");        } finally { if (ps != null) {     try {         ps.close();     } catch (SQLException e) {         throw new HibernateException("Unable to close prepared statement.");     } }        }        return result;    }}

像这样注释实体PK:

@Id@GenericGenerator(name="seq_id", strategy="my.package.StringKeyGenerator")@GeneratedValue(generator="seq_id")@Column(name = "TABLE_PK", unique = true, nullable = false, length = 20)public String getId() {    return this.id;}

由于Eclipse中的错误,可能会引发一个错误,即

seq_id
在持久性单元中未定义generator()。将此设置为警告,如下所示:

  1. 选择 窗口»首选项
  2. 展开 Java持久性»JPA»错误/警告
  3. 点击 查询和生成器
  4. 在持久性单元中未 将Set Generator定义 为:
    Warning
  5. 单击 确定 以应用更改并关闭对话框


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426617.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号