Part 2: Building API
- Download the source code Attach:advera.zip
- Import it to IntelliJ IDEA
- Add your Postgres Database credentials in
application.properties
file
spring.datasource.url= jdbc:postgresql://localhost:5432/Your_Database spring.datasource.username= Your_Postgres_Username spring.datasource.password= Your_Password
- Run
Project Structure
src └── main ├── java │ └── com │ └── advera.advera │ ├── AdveraApplication.java │ ├── controller │ │ └── AdvertisementController.java | | └── PublisherController.java │ ├── exception │ │ └── ResourceNotFoundException.java │ └── model │ ├── Advertisement.java │ └── Publisher.java │ └── repository │ ├── AdvertisementRepository.java │ └── PublisherRepository.java └── resources ├── application.properties ├── data-postgres.sql ├── static └── templates ├── showPublishers.ftl
Load Initial Data
- You can create
data-postgres.sql
files in yoursrc/main/resources
folder to automatically load initial data when the application starts. In this file you can add someINSERT
statements. In order to avoid inserting duplicate data, we shouldTRUNCATE
command in the beginning ofINSERT
statements.TRUNCATE
quickly removes all rows from a table or a set of tables. As we have a Many-To-Many relationship, then make sure you add all tables.
- You can create
TRUNCATE publishers,advertisements,ads RESTART IDENTITY; INSERT INTO publishers(name, publisher_address, publisher_contact) VALUES('Adsense','Mountain View, California, United States','info@adsense.com'); INSERT INTO publishers(name, publisher_address, publisher_contact) VALUES('Elanaat','Tartu mnt 4590','info@elanaat.com');
Using Freemaker template engine
The below diagram demonstrates the relationships between model, controller, and the Freemaker template. Follow this digram to make some small changes in your source code to generate text output (HTML web pages).
- Add Freemaker dependency to
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
- Add these two lines to
application.properties
file:
- Add Freemaker dependency to
spring.freemarker.template-loader-path=classpath:/templates spring.freemarker.suffix=.ftl