addressListRoute
layout: default title: Demo: Address List Route
Up to this point we haven't interacted with a database using Spring REST. Remember the JPAVideoStore project we created during JPA week? We are going to use this pre-configured backend to create some resource routes for Address and Actor objects.
- Find your JPAVideoStore project. Run one of your JUnit tests to make sure that your connections are still up and running.
-
If you broke or lost this project, use the provided solution in the resources directory.
-
Create a separate Spring Starter Project called VideoStoreREST.
- Walk through the standard process of creating a Spring Boot project.
- Give your project a base package of
com.example. - Set Type to Gradle, Java Version to 8, and Packaging to War.
-
Be sure to include the Spring Web, Spring Data JPA, and MySQL Driver dependency bundles.
-
Edit the new project's
settings.gradlefile at the same level as yourbuild.gradlefile. Add JPAVideoStore as a sub project.rootProject.name = 'VideoStoreREST' includeFlat 'JPAVideoStore' -
Add your JPAVideoStore project as a dependency to the
build.gradlefile, then run a Gradle refresh.dependencies { implementation project(':JPAVideoStore') // ... } -
Configure your
portanddatasourcein theapplication.properties.#### PORT CONFIG #### server.port=8081 #### MYSQL DATASOURCE #### spring.datasource.url=jdbc:mysql://localhost:3306/sdvid?useSSL=false&&useLegacyDatetimeCode=false&serverTimezone=US/Mountain spring.datasource.username=student spring.datasource.password=student spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -
Create two packages, one called
com.example.videostorerest.dataand the other calledcom.example.videostorerest.controllers. -
Create files called
AddressDAO,AddressDAOImpl, andAddressControllerin their respective packages. -
Annotate your DAOImpl as
@Transactionaland@Service. Include the EntityManager as a field.@Transactional @Service public class AddressDAOImpl implements AddressDAO { @PersistenceContext private EntityManager em; } -
Annotate the controller as a
@RestControllerand@Autowirein yourAddressDAO. Give the class a@RequestMappingso that all the subsequent routes are preceded byapi/.
@RestController
@RequestMapping("api")
public class AddressController {
@Autowired
private AddressDAO addressDAO;
}
- Write a single DAO method that uses JPQL to query the database to retrieve and return a list of addresses.
public List<Address> findAll(){
String query = "Select a from Address a";
return em.createQuery(query, Address.class).getResultList();
}
- Back in your controller, write a method that is mapped by the path
/api/addresseswhich returns the result of calling the DAO method we just wrote.
@RequestMapping(path="addresses", method=RequestMethod.GET)
public List<Address> index(){
return addressDAO.findAll();
}
- Run the program and hit the route
http://localhost:8080/api/addressesin Postman. View the returned json data.