Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Next value from sequence with spring hibernate

I am using spring jpa repository with hibernate to save entites to my oracle database. How I can get the next value of my oracle database sequence using Spring-Hibernate?

This is my Event class :

@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;
  }
}

I need to get the next value of the sequence once for the all event series in the event resolver.

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);
        }

    }
}

Thanks for any kind of help..

like image 381
Ron Badur Avatar asked Sep 15 '17 13:09

Ron Badur


2 Answers

Finally I Solved my problem in the Spring way, All you need is to add a native query in the JpaRepository like this:

public interface EventRepository extends JpaRepository<Event, Long> {

 @Query(value = "SELECT seq_name.nextval FROM dual", nativeQuery = 
        true)
 Long getNextSeriesId();
like image 85
Ron Badur Avatar answered Sep 19 '22 11:09

Ron Badur


With Spring 5, you can use one of their built-in classes for this task like OracleSequenceMaxValueIncrementer

See all the available options in this package: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/incrementer/package-summary.html

like image 39
Gustavo Passini Avatar answered Sep 18 '22 11:09

Gustavo Passini