Connect Spring Boot JPA to the database
This article describes how to add JPA as a persistence method in the Spring Boot project.
Modify pom. xml dependency
Unlike jdbc described in the previous article, spring-boot-starter-jdbc can be changed to spring-boot-starter-data-jpa. Of course, the database driver package is also indispensable, as shown below:
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-data-jpa
Note: If you want to use JDBC and JPA together, Spring Boot is supported. You only need to add JDBC and JPA dependencies to pom. xml. Modify attribute configuration file
Add attributes related to JPA in the attribute configuration file. Note that these attributes are not required. If you only add the dataSource url \ username \ password \ driver-class-name, other configurations related to JPA are optional.
spring.jpa.database=spring.jpa.show-sql=spring.jpa.properties.xxxxxxx=spring.jpa.generate-ddl=spring.jpa.open-in-view=spring.jpa.database-platform=spring.jpa.hibernate.ddl-auto=spring.data.jpa.repositories.enabled=spring.jpa.hibernate.naming-strategy.xxxxxxx=
If you are familiar with JPA, you should be familiar with the functions of these differences by name.
Traditionally, JPA object classes are specified in the persistence. xml file. Using Spring Boot, this file is unnecessary because it uses "entity scanning". By default, all the packages under the main configuration @ EnableAutoConfiguration or @ SpringBootApplication will be scanned. Any class that uses annotation @ Entity, @ Embeddable or @ MappedSuperclass will be managed.
Java code instance one interface one Controller
We create an interface IScoreDao. java, and then we inherit the framework to provide us with a good Interface Repository or CrudRepository (CrudRepository inherited from Repository), which provides us with basic database operations.
package org.springboot.sample.dao;import java.util.List;import javax.transaction.Transactional;import org.springboot.sample.entity.Score;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.CrudRepository;import org.springframework.data.repository.query.Param;public interface IScoreDao extends CrudRepository
{ @Transactional @Modifying @Query("update Score t set t.score = :score where t.id = :id") int updateScoreById(@Param("score") float score, @Param("id") int id); @Query("select t from Score t ") List
getList();}
Note: If you use the modify, add, or delete operations, you must add the @ Transactional annotation to the interface or corresponding method. Otherwise, an exception is thrown.
Entity Score. java
Package org. springboot. sample. entity; import java. io. serializable; import java. util. date; import javax. persistence. column; import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. id; import javax. persistence. table;/*** score ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 12, 2016 */@ Entity @ Table (name = "score ") public class Score imple Ments Serializable {private static final long serialVersionUID = 8127035730921338189L; @ Id @ GeneratedValue private int id; @ Column (nullable = false, name = "STUDENTID") // here, when I use the specified database column, it does not work if I use lower case letters. It is normal if I change it to upper case letters. If you have the same problem, try again. Private int stuId; @ Column (nullable = false, name = "SUBJECTNAME") private String subjectName; @ Column (nullable = false) private float score; @ Column (nullable = false, name = "EXAMTIME") private Date examTime; // Save the get and set methods (occupying Article space )}
ScoreController. java
Package org. springboot. sample. controller; import java. util. list; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springboot. sample. dao. IScoreDao; import org. springboot. sample. entity. score; import org. springframework. beans. factory. annotation. autowired; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. restController; @ RestController @ RequestMapping ("/score") public class ScoreController {private static final Logger logger = LoggerFactory. getLogger (ScoreController. class); @ Autowired private IScoreDao scoreService; @ RequestMapping ("/scoreList") public List
GetScoreList () {logger.info ("Score set read from database"); // test and update logger.info ("number of updated rows:" + scoreService. updateScoreById (88.8f, 2); scoreService. delete (23); return scoreService. getList ();}}
Finally, Spring automatically creates an implementation class for the interface that inherits the CrudRepository interface. We only need to directly use the annotation @ Autowired injection when using it (there is no need to add annotation such as @ Component and @ Repository on the IScoreDao interface ).
Also, for the sake of simplicity, I will directly use the database operations in the Controller. In actual projects, this is not recommended. The role of IScoreDao is database persistence, we should also have a Service (such as ScoreService) to call the IScoreDao method, and then call the method in Service in the Controller. The reason is that the database access layer is an interface definition method. The preceding annotations inject SQL statements and parameters without specific code logic processing. If we want to execute logical processing before or after SQL Execution, it can only be in Service or Controller (not recommended.
We strictly follow this method (the persistence layer is only related to SQL, and no logical processing is defined through interfaces). This is a thorough persistence layer. The stricter the standard system, to some extent, is more conducive to code management and iterative development of project code.
Of course, if you really want to implement your class implementation class, an instance code will be attached below. Before that, let's take a look at the image:
This figure shows the interface instance created by Spring using a dynamic proxy. We can see that it uses the SimpleJpaRepository class, so if we implement our own RepZ runtime? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> encrypt/decrypt/atcTKtc/encrypt/HU8sTju + aggregate + sb7OxL3pydxKUEEgz + aggregate =" engineering structure "src =" http://www.bkjia.com/uploads/allimg/160114/040T15624-1.png "title =" \ "/>
When you are familiar with one of the methods for persistent data, the others are similar.