0

I have an auto-generated sequence in my model class like this:

@Entity
@Table(name="track")
@NamedQuery(name="track.findAll", query="SELECT t FROM Track t")
public class Track  {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private long id;
...

I want to display the next value in an "insert.jsp" -somewhat like this:

<table>
    <form:form action="save.do" method="post" modelAttribute="track">
    <tr>
        <td>Track Id:</td>
        <td><form:input path="id" value="${track.getNext()}" readonly="true"/></td>    
    </tr>

{track.getNext()} doesn't work as of now. What is the best way to do this? I tried using this piece of code in my model class. My context lookup path is throwing an error. Is this the right place to write this code? If not, where should I put it? What should be the context lookup path? In my code, it is the path to Persistence.xml.

  @PersistenceContext
  public static long getNext() throws Exception {
     Context initCtx = new InitialContext();
     javax.persistence.EntityManager em = (javax.persistence.EntityManager) 
                initCtx.lookup("src.main.resources");
     Query q = (Query) em.createNativeQuery("SELECT TRACK_ID_SEQ.nextval from DUAL");
    BigDecimal result=(BigDecimal)((javax.persistence.Query) q).getSingleResult();   
        return result.longValue();
    }
javagirl
  • 41
  • 1
  • 7
  • Please complete your problem description by including the entire error message: summary, location, and stack trace (if any ). – Prune Nov 04 '15 at 02:18
  • Your problem is incorrect one. You should never get an id value before it have been assigned by Hibernate. Why do you do it? – v.ladynev Nov 04 '15 at 07:07
  • Attention: `nextVal` is _not_ a read only function - it always increments the sequence as well. And you should be aware that the next ID generated in Hibernate may differ from the one from the sequence - see http://stackoverflow.com/questions/12745751/hibernate-sequencegenerator-and-allocationsize for more on that. Even if you can workaround all these problems: What happens if two users open the page at the same time? At least one of them would see an ID that is not the ID of _his_ entity. – Tobias Liefke Nov 04 '15 at 11:31

0 Answers0