I have a class mapped as an Entity to persist it in a database. I have an id field as the primary key so every time the object is persisted the value of the id is retrieved
See another question/answers on the subject of using sequence defined elsewhere than id fields. You can create a fake entity with one field (of type Long id). Connect it to the sequence you defined in the DB. Then create a CrudRepository implementation for that entity and call its save() method with an empty instance of the fake entity object you defined. Hibernate will run for you a "select YOUR_SEQ.NEXTVAL from dual" query.
I just want to have a method which call nextval on a sequence associated with "code" field, and returns the value. What's the best way to do it in JPA with annotations?
Both solutions sounds a bit ugly. Maybe you could simply use a random generator like a UUID generator.
Actually, you didn't mention anything about the uniqueness of the code
(and the JPA annotations don't show it must be unique). Why don't you return a random int?