A guide to Annotations in Spring Boot - Part 1
If you are a Spring Boot developer, or you just started the road in this town, you must have used various kinds of annotations. When I started my first project, I used them just to get the project done but then I started exploring them and jotted them down for my easy understanding. Here I list some of the annotations which are commonly used in entity class with their meanings and use.
For this post, I am going to cover all the annotations covered in this piece of code:
@Entity
@Table(name="User")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class User {
@Id
@GeneratedValue
private Long id;
@Column(name = "USER_NAME", length = 50, nullable = false, unique = true)
private String userName;
@Column(name="FIRST_NAME", length = 50, nullable = false)
private String firstName;
@Column(name="LAST_NAME", length = 50, nullable = false)
private String lastName;
@Column(name="EMAIL", length = 50, nullable = false)
private String email;
@Column(name = "ROLE", length = 50, nullable = false)
private String role;
}
Entity
- JPA Annotation:
@Entity
- Used to mark a POJO class in Java as persistence table in the database
- It converts each variable in the POJO class as a field/column in table
Eg:
@Entity
public class Demo{
}
Table
JPA Annotation:
@Table
This is used to name the table. We can change entity name using this. And it is not necessary to have the same entity and table name.
NoArgsConstructor
JPA Annotation:
@NoArgsConstructor
This annotation is provided by Lombok dependency
It generates a default constructor for class with no parameters
AllArgsConstructor
JPA Annotation:
@AllArgsConstructor
This annotation is provided by Lombok dependency
It generates a constructor requiring an argument for every field/variable in the annotated class(entity)
Getter
JPA Annotation:
@Getter
Provided by Lombok dependency
Provides getter methods for every field
Setter
JPA Annotation:
@Setter
Provided by Lombok dependency
Provides setter methods for every field
ToString
JPA Annotation:
@ToString
Provided by Lombok dependency
Provides
toString()
method for the annotated class
Id
JPA Annotation:
@Id
Marks the field as the primary key in the table
GeneratedValue
JPA Annotation:
@GeneratedValue
This is to specify how the primary key must be generated.
It has many strategies for generating keys, default is Auto which is like Auto_Increment in MySql
Column(name, length, nullable, unique)
JPA Annotation:
@Column
This is to specify the column properties like name, length of value(if a string), it can be null or not and then unique which defines if the column value should be unique
I will bring more in part 2 of this post. This is my first post, so I would love to hear what I can do better.