In this project, we will create a REST API to see the list of user details where we can get a username, email ID, and contact number. So let's create a model of a user where the class name is UserModel.kt.
Here is the code of the model class:
@Entity
@Table(name="user_jpa")
@EntityListeners(AuditingEntityListener::class)
data class UserModel(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
var id: Long = 0,
@NotBlank
@Column(name = "name")
var name: String ?= null,
@NotBlank
@Column(name = "email")
var email: String ?= null,
@NotBlank
@Column(name = "contact_number")
var contact_number: String ?= null
)
Here, our UserModel class has the following fields:
- id: Primary key with auto increment
- name: (NOT NULL field)
- email: (NOT NULL field)
- contact_number: (NOT NULL field)
Unlike JDBC, you don't need to create any table manually in your database. JPA will create a table using the UserModel. Let's look at how to create a table in our database using this UserModel object:
- @Entity: All your domain models must be annotated with this annotation. This annotation is used to mark the class as a persistent Java class.
- @Table: This annotation is used to provide the details of the table. The entity will be mapped by it.
- @Id: This is used to define the primary key.
- @GeneratedValue: This annotation is used to define the primary key generation strategy. In the preceding case, we have declared the primary key as an auto increment field.
- @NotBlank: This is used to verify that the annotated field is not null or empty.
- @Column: This is used to verify the properties of the column that will be mapped to the annotated field.