使用 spring hibernate 从序列中获取下一个值

新手上路,请多包涵

我正在使用带有 hibernate 的 spring jpa 存储库将实体保存到我的 oracle 数据库中。如何使用 Spring-Hibernate 获取 oracle 数据库序列的下一个值?

这是我的事件类:

 @Entity
public class Event {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private Long seriesId;

  private String description;

  public Event() {
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Long getSeriesId() {
    return seriesId;
  }

  public void setSeriesId(Long seriesId) {
    this.seriesId = seriesId;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }
}

我需要为事件解析器中的所有事件系列获取一次序列的下一个值。

 public class EventResolver {

    @Autowired
    private EventRepository eventRepository;

    public void createSeriesOfEvents(List<EventAPI> eventsToCreate){

        Long seriesId = null; // TODO: Get the series id from database sequence

        for (EventAPI currEvent : eventsToCreate){
            Event newEvent = new Event();
            newEvent.setDescription(currEvent.description);
            newEvent.setSeriesId(seriesId);
            eventRepository.save(newEvent);
        }

    }
}

感谢您提供任何帮助..

原文由 Ron Badur 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
2 个回答

最后我以 Spring 的方式解决了我的问题,你所需要的只是在 JpaRepository 中添加一个本地查询,如下所示:

 public interface EventRepository extends JpaRepository<Event, Long> {

 @Query(value = "SELECT seq_name.nextval FROM dual", nativeQuery =
        true)
 Long getNextSeriesId();

原文由 Ron Badur 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Spring 5,您可以使用其中一个内置类来完成此任务,例如 OracleSequenceMaxValueIncrementer

查看此包中的所有可用选项: https ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/incrementer/package-summary.html

原文由 Gustavo Passini 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题