reset password

Create a REST API Using Spring Boot

2. Data Access

Create a MySQL database sbrest and use the following SQL script to populate the database:

Edit the file src/main/resources/application.properties to include the following four properties:

spring.datasource.url=jdbc:mysql://localhost/sbrest?useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=cysun
spring.datasource.password=abcd

And of course you should change the username and password to match the setup of your database.

Add a data model class User to the project under the edu.csula.sbrest.model package:

There are a few things worth mentioning about this model class: a) we use a number of JPA annotations to map this class to the users table in the sbrest database, b) the hash field in the class will be used to stored user password encrypted using the bcrypt function, and c) the @JsonIgnore annotation on the hash field tells Jackson (the library used to convert between Java objects and JSON) not to include the hash field when converting a User object to JSON -- this is to ensure that user password is not included in the results sent to the client.

Add the following data access code to the project:

DAO stands for Data Access Object, which is a Java EE design pattern for data access. Typically there is an interface (e.g. UserDao) and an implementation class (e.g. UserDaoImpl) involved in a DAO. The interface specifies what methods the data access layer provides to the application, and the implementation implements these methods using a particular technology, e.g. JPA or JDBC or something else depending on the underlying data store.

Now to test our project, add a simple controller under the edu.csula.sbrest.controller package:

To run the project in Eclipse, right click on SbrestApplication.java under the edu.csula.sbrest package and select Run As -> Java Application -- remember that the project is packaged in a JAR file with its own embedded Tomcat server, so we run it as a regular Java application instead of using "Run on Server" to deploy it to an existing server. When the application is running, use a browser to open the URL http://localhost:8080/users and you should see the users displayed as a JSON array.

 

This page has been viewed 1153 times.