Getting Next value from sequence with spring hibernate

Ron Badur :

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..

Ron Badur :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470500&siteId=1
Recommended