Difference in Declaration of a @Generatedvalue Class

Asked

Viewed 40 times

1

What’s the difference when I declare a class informing the @GeneratedValue(strategy = GenerationType.IDENTITY) and not informing, since the database manager will coordinate the primary key? I’m asking because informing or not, created the tables in the same way.

@Entity
public class Status implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="status_id")
    private Long id;

    @Column(name="status_descricao")
    private String descricao;**

1 answer

1


Table is normally created without the annotation @GeneratedValue, but when entering a record, the value of the field that corresponds to the primary key must be manually assigned, because when you use the @GeneratedValue, automatically the column value is incremented.

In your case, the field id is automatically incremented every time a new record is inserted, because of the annotation. If not use, each time you need to set a unique value for the column.

Example:

Status status = new Status();
status.setId(1);
status.setDescricao("Primeira objeto com id manual");

Status statusObj = new Status();
statusObj.setId(2);
statusObj.setDescricao("Segundo objeto com id manual");
  • 1

    I realized this. At the time of testing with Postman, if there is no @Generatedvalue annotation, the data is not entered in the database. Then put this note when I send a POST via Postman it can write to the database. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.