JPA / Hibernate5通过序列名称获取序列nextval

时间:2018-11-09 07:57:41

标签: java hibernate jpa sequence

如何通过sequence nextvalJPAHibernate 5中获得sequence name

我对TEST_SEQ数据库中的以下OracleANOTHER_NAME_SEQ数据库中的Postgresql进行了排序。

我需要具有以下签名的方法

public Long getSequenceByName(String sequenceName){}

当我调用此方法时,它必须从现在使用的数据库中返回nextval

我有两个主意,但是不适合。

1)在属性中存储每个数据库的本机查询,并编写如下方法:

@Value("${query}")//"SELECT {name}.NEXTVAL FROM DUAL"
private StringQuery;

public Long getSequenceByName(String sequenceName){
    uery q = em.createNativeQuery(StringQuery.replace("{name}", sequenceName));
    return (java.math.BigDecimal) q.getSingleResult();
  }

但是我需要使用占位符存储查询字符串,并将占位符替换为序列名称,并存储每个数据库的查询。

2)创建仅具有一个字段@Id的实体。插入实体和getId(序列值)。

但是如果在不同的DB中,序列名称不同-???

3)使用this。但是对于休眠3来说,我不知道这是否是一个好方法。

编辑:

我尝试此解决方案:

@Component
public class SequenseRepository {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public Long getID(final String sequenceName) {
        final List<Long> ids = new ArrayList<>(1);

        Session session = em.unwrap(Session.class);
        session.doWork(connection -> {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect =  dialectResolver.resolveDialect((DialectResolutionInfo) connection.getMetaData());
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
                resultSet = preparedStatement.executeQuery();
                resultSet.next();
                ids.add(resultSet.getLong(1));
            }catch (SQLException e) {
                throw e;
            } finally {
                if(preparedStatement != null) {
                    preparedStatement.close();
                }
                if(resultSet != null) {
                    resultSet.close();
                }
            }
        });

        return ids.get(0);
    }
}

我得到了认可:

java.lang.ClassCastException: oracle.jdbc.driver.OracleDatabaseMetaData cannot be cast to org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo&#xd;

1 个答案:

答案 0 :(得分:2)

由于这篇文章enter link description here

,我找到了解决方案
    public interface SequenceRepository {
    int getNext(String sequenceName);
   }

以及每个数据库的实现:

@Profile("oracle")
@Component("oracleSequenceRepository")
public class OracleSequenceRepository implements SequenceRepository{

    private final DataSource dataSource;

    @Autowired
    public OracleSequenceRepository(@Qualifier("dataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Transactional(readOnly = true)
    @Override
    public int getNext(String sequenceName) {
        AbstractSequenceMaxValueIncrementer incr = new OracleSequenceMaxValueIncrementer(this.dataSource, sequenceName);
        return incr.nextIntValue();
    }
}

@Profile("postgre")
@Component("postgresSequenceRepository")
public class PostgreSequenceRepository implements SequenceRepository{

    private final DataSource dataSource;

    @Autowired
    public PostgreSequenceRepository(@Qualifier("dataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Transactional(readOnly = true)
    @Override
    public int getNext(String sequenceName) {
        AbstractSequenceMaxValueIncrementer incr = new PostgresSequenceMaxValueIncrementer(this.dataSource, sequenceName);
        return incr.nextIntValue();
    }
}