To make our application product-ready, we need to enhance the storage of the configurations. One of the most common ways to store user credentials is to use a database to handle user information, roles, and their mappings between each other. In order to have our database configuration ready, we first need to add the spring-boot-starter-data-jpa dependency, which provides a set of convenient dependency descriptors that help us use JPA for database connectivity:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
We will use the H2 database in our example for its simplicity and its In-memory database support. You can use your favorite database instead by simply changing the Datasource configuration. Here is the Maven dependency for H2:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
First, we need to define the JPA entities for the User and Role classes, as follows:
@Entity
@Table(name = "app_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns =
@JoinColumn(name = "user_id",
referencedColumnName = "id"),
inverseJoinColumns =
@JoinColumn(name = "role_id",
referencedColumnName = "id"))
private List<Role> roles;
// getters & setters
}
@Entity
@Table(name="app_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="role_name")
private String roleName;
// getters & setters
}