我正在使用带有hibernate的spring jpa存储库来保存我的oracle数据库的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);
}
}
}
感谢您提供任何帮助..
答案 0 :(得分:15)
最后我以Spring的方式解决了我的问题,你只需要在JpaRepository中添加一个本机查询,如下所示:
public interface EventRepository extends JpaRepository<Event, Long> {
@Query(value = "SELECT seq_name.nextval FROM dual", nativeQuery =
true)
Long getNextSeriesId();
答案 1 :(得分:1)
您可以在JPA中使用此方法:
Query q = em.createNativeQuery("select seq_name.nextval from dual");
return (Long)q.getSingleResult();
答案 2 :(得分:0)
像这样注释你的id属性:
@Id
@GeneratedValue(generator = "idSequence")
@SequenceGenerator(schema = "MYORASCHEMA", name = "idSequence", sequenceName = "MY_ORACLE_SEQ_NAME", allocationSize = 1)
@Column(name="ID")
private Long id;
答案 3 :(得分:0)
在Spring 5中,您可以使用其内置类之一来完成此任务,例如OracleSequenceMaxValueIncrementer
查看此软件包中的所有可用选项:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/incrementer/package-summary.html