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:
- Close any other open projects for now
- Create a Spring project named ScoreData
- Add Dev Tools, SQL – Spring Data JDBC and the MySQL Driver to the project
- In the ‘Application’ class, implement CommandLineRunner
- Add the required public void run(String… args) throws Exception method
- Mark the class as @Transactional
- Add the Score class
- Decorate the Score class
- Inject the EntityManager as a @PersistenceContext
- Write some JPA code in the run method
- 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