Get max id on JPA

Posted: February 19, 2013 in web

Service

...
 @PersistenceContext(unitName = "someDB")
 private EntityManager entityManager;

 private Integer getMaxJobId() {
 Integer maxId = (Integer) entityManager.createNamedQuery(JOB_GET_MAXID).getSingleResult();
 return maxId + 1;
 }
...

Entity

@Entity
@Table(name = "Jobs")
@NamedQueries({ @NamedQuery(name = "Job.getMaxID", query = "Select max(b.id) as maxid from Job b"),
 @NamedQuery(name = "Job.removeTestData", query = "delete from Job where id > 87") })
public class Job implements Serializable {

/**
 *
 */
 private static final long serialVersionUID = -8718855207979969734L;

@Id
 @Column(name = "Id", nullable = false)
 private Integer id;
...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s