Skip to content

Spring Databases, PostgreSQL

Sharina Stubbs edited this page Jan 28, 2020 · 1 revision

Class Demo

Get DB dependencies

(Tell Spring to connect with Postgres)

Two key dependencies

(1) JPA - the data storage integration package

  • java can integrate with any database
  • It's the java persistance API
  • Makes modular apps nicely
  • stands for Java Persistence API... though it was renamed in 2019 to Jakarta Persistence

(2) PostgreSQL

Copy-paste dependencies from lab instructions (see link above) Import gradle changes

Change the architecture if needed:

Create a package called models and a package for controllers and put appropriate files into each package

Add @Entity on top of the class and an id to our instance variables.

@Entity
public class Album {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  Long id;
  public String emotionName 

application properties within resources

Add the following to the application.properties file, found within Resources package

spring.datasource.url=jdbc:postgresql://localhost:5432/emotions <----- note that the last line is the database name
spring.datasource.username=ncarignan
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create <------ adds a table to the database just once 

Go to psql shell

make a database

psql
CREATE DATABASE emotions;
\c emotions 
\dt

Make a new class

Put it in the Models package.

Call it EmotionRepository.java

//JpaRespository <Type, IDentifier Type
public interface EmotionRepository extends JpaRepository<Emotion, Long> { }

This code knows we are connected to postgress, and will set us up to update, delete, get things, filter things, etc within the database.

Emotion is the class, and Long is the type that ID is set to. In our case, it was Long Id.

Go to HomeController

First thing, in public class HomeController, load the emotionaRepository

public class HomeController {
  @Autowired
  EmotionRepository emotionRepository;
  
  your other code from prior work...
  blah...
  blah...
}

Replace the Model information in the appropriate method, with:

@GetMapping
public String getTheEmotions(Model m) {
  List<Emotion> feelings = emotionRepository.findAll(); <---- setting it as a list
  m.addAttribute("feelings", feelings);
  return "emotions"
}

Check database from terminal

\dt
\dt emotion <---- to see contents of table

Insert Data Into DB

INSERT INTO emotion (emotion_name, reason, strength) VALUES ('sleepy', 'lack of sleep', 9)

check database

SELECT * FROM emotion;

Go to Emotion.java

Make sure there's a default constructor in Emotion.java

public emotion () {}

Go back to applications.

Comment out: spring.jpa.hibernate.ddl-auto=create so that we don't override ourselve every time after the first database load.

... or change to: spring.jpa.hibernate.ddl-auto=update

Post data

Adding a form

Go to HTML page

Make a form

<form action="/emotion" method="POST">
  <input type="text" name= "emotionName="> name
  <input type="text" name= "emotionStrength="> strength
  <input type="text" name= "emotionReason="> reason
  etc

Note that you cannot DELETE anything within a form. Forms only GET and POST.

POST requests change the state of the world; GET requests do not. Google finds all GET links it can find when it crawls through the website.

Go to Controller page (like HomeController)

Create a redirect so when form is filled out, the user is then directed over to another page.

@PostMapping("/emotions")
public RedirectView addTheEmotions() {   <---- want to return a redirect
  return new RedirectView("/emotions"); <------- creating an instance of a class here
}

Alternatively, can get more complicated - parameters can map to the body - and add data to the database!

@PostMapping("/emotions")
public RedirectView addTheEmotions(String emotionName, String reason, int strength) { 

  // add the stuff put into the form into the database
  Emotion em = new Emotion(emotionName, strength, reason);
  emotionRepository.save(em);  

  return new RedirectView("/emotions");
}

Should now see the stuff the person put into the form in the database, and the same stuff on the emotions page.

Clone this wiki locally