Spring, JPA and Databases

JDBC and Spring is a bit more complicated than most other activities. There are a lot of steps. Some will inevitably be missed here. But I’ll give it a try:

  1. Close any other open projects for now
  2. Create a Spring project named ScoreData
  3. Add Dev Tools, SQL – Spring Data JDBC and the MySQL Driver to the project
  4. In the ‘Application’ class, implement CommandLineRunner
  5. Add the required public void run(String… args) throws Exception method
  6. Mark the class as @Transactional
  7. Add the Score class
  8. Decorate the Score class
  9. Inject the EntityManager as a @PersistenceContext
  10. Write some JPA code in the run method
  11. Update the application.properties file

The Score Class

@Entity
@Table(name = "score")
public class Score {

	@Id 
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public int id;

	public int wins;
	public int losses;
	public int ties;
	
}

The Application Class

@SpringBootApplication
@Transactional
public class PersistentScoreApplication implements CommandLineRunner {
	
	@PersistenceContext
	private EntityManager entityManager;

	public static void main(String[] args) {
		SpringApplication.run(PersistentScoreApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
	
		Score score = entityManager.find(Score.class, 1);
		System.out.println(score.wins);
		score.wins++;
		
	}
}

application.properties

spring.datasource.url=jdbc:mysql://rps.cyvpttibbqrc.us-east-1.rds.amazonaws.com/ROSHAMBO
spring.datasource.username=cameronmcnz
spring.datasource.password= ASK THE INSTRUCTOR
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.thymeleaf.enabled=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true