2017-09-15 89 views
1

我正在使用spring jpa存储库和hibernate一起将实体保存到我的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); 
     } 

    } 
} 

感谢任何形式的帮助..

+0

为什么?将正确的注释应用到'@ ID'字段,Hibernate将为你做这一切。例如,请参阅:https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Sequence_objects http://tech.zooplus.com/sequences-in-hibernate/ –

+0

我希望整个系列(系列)具有相同的值可以是4-5个事件),所以当我创建'Event'实体时不能生成它。我必须在'createSeriesOfEvents'方法 –

回答

1

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

public interface EventRepository extends JpaRepository<Event, Long> { 

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

您可以使用JPA这种方法:

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

中从我可以获取'em'对象的地方执行它? –

+0

'em'表示EntityManager,你可以自动装配它 – StanislavL

0

标注您的ID属性,像这样:

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

我不希望每个对象都会得到他自己的ID,我想给所有系列(4-5个事件类型的对象)提供相同的系列ID –

+0

你有没有父系表的系列? – slambeth

+0

不,我只是想要创建一系列事件的选项 - 这意味着少数事件具有相同的系列ID但不同的ID –