programing

스프링 최대 절전 모드가 있는 시퀀스에서 다음 값 가져오기

subpage 2023. 10. 21. 10:27
반응형

스프링 최대 절전 모드가 있는 시퀀스에서 다음 값 가져오기

hibernate가 있는 spring jpa 저장소를 사용하여 entites를 내 오라클 데이터베이스에 저장하고 있습니다.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);
        }

    }
}

어떤 도움이든 감사합니다.

드디어 봄의 방법으로 문제를 해결했습니다. JpaRepository에 다음과 같이 기본 쿼리를 추가하기만 하면 됩니다.

public interface EventRepository extends JpaRepository<Event, Long> {

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

Spring 5를 사용하면 Oracle SequenceMaxValue와 같은 기본 제공 클래스 중 하나를 이 작업에 사용할 수 있습니다.인크리멘터

이 패키지에서 사용 가능한 모든 옵션 보기: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/incrementer/package-summary.html

다음과 같이 ID 속성에 주석을 달 수 있습니다.

@Id
@GeneratedValue(generator = "idSequence")
@SequenceGenerator(schema = "MYORASCHEMA", name = "idSequence", sequenceName = "MY_ORACLE_SEQ_NAME", allocationSize = 1)
@Column(name="ID")
private Long id;

JPA에서는 다음 방법을 사용할 수 있습니다.

Query q = em.createNativeQuery("select seq_name.nextval from dual");
return (Long)q.getSingleResult();

언급URL : https://stackoverflow.com/questions/46240529/getting-next-value-from-sequence-with-spring-hibernate

반응형