Spring Boot JPA Connection Database

Source: Internet
Author: User

This article describes how to add JPA as a persistence method in the Spring Boot project.

modifying pom.xml dependencies

Different from the one described in the previous article is SPRING-BOOT-STARTER-JDBC modified to SPRING-BOOT-STARTER-DATA-JPA, of course, the database driver package is also indispensable, as follows:

 <!--MYSQL -- <dependency>    <groupId>Mysql</groupId>    <artifactid>Mysql-connector-java</artifactid> </Dependency> <!--Spring Boot JPA --- <dependency>    <groupId>Org.springframework.boot</groupId>    <artifactid>Spring-boot-starter-data-jpa</artifactid> </Dependency>

Note: If you want JDBC and JPA to work together, Spring Boot is supported, and you only need to add JDBC and JPA dependencies to Pom.xml. No additional special processing is required, see the "Spring-boot JDBC Connection database" for a description of the use of JDBC.

Modifying a property configuration file

Adding JPA-related properties to the property profile, note that these are not necessary, and we can use them only if we add DataSource url\username\password\driver-class-name, and other configurations about JPA are optional.

Spring. JPA. Database=spring. JPA. Show-sql=spring. JPA. Properties. xxxxxxx=spring. JPA. Generate-ddl=spring. JPA. Open-inch-view=spring. JPA. Database-platform=spring. JPA. Hibernate. DDL-auto=spring. Data. JPA. Repositories. Enabled=spring. JPA. Hibernate. Naming-strategy. xxxxxxx=

Familiarity with JPA based on the name should basically know the effect of these distinctions.

Traditionally, JPA entity classes are specified in the Persistence.xml file. With spring Boot, this file is not necessary because it uses "entity scan", and by default all packages under the master configuration @EnableAutoConfiguration or @SpringBootApplication will be scanned. Any class that uses annotations @Entity, @Embeddable or @MappedSuperclass will be managed.

Java Code Instance
    • An interface
    • A controller

We create an interface Iscoredao.java, and then we inherit the framework to provide us with a good interface Repository or Crudrepository (Crudrepository inherits from Repository), This provides us with a basic way to manipulate the database.

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<score, integer> {@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<score> GetList ();}

Note that if you use modifications, additions, and deletions, you must add @Transactional annotations above the interface or the corresponding method, or an exception will be thrown.

Entity class Score.java

 Packageorg.springboot.sample.entity;Importjava.io.Serializable;ImportJava.util.Date;ImportJavax.persistence.Column;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.Id;Importjavax.persistence.Table;/** * Score * * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create 2016 1 Month 12th * /@Entity@Table(name ="Score") Public  class score implements Serializable {    Private Static Final LongSerialversionuid =8127035730921338189L@Id    @GeneratedValue    Private intId@Column(Nullable =false, name="StudentID")//To say here, I use the specified database column when the use of lowercase will not work, the change to uppercase is normal. Do not know why, if you encounter the same problem can be tried.     Private intStuid;@Column(Nullable =false, name="Subjectname")PrivateString Subjectname;@Column(Nullable =false)Private floatScore;@Column(Nullable =false, name="Examtime")PrivateDate Examtime;//Omit Get, set method (occupy 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<score> getscorelist () {Logger. Info("read score collection from database");Test Update Database Logger. Info("Number of rows updated:"+ Scoreservice. Updatescorebyid(88.8F2));Scoreservice. Delete( at);Return Scoreservice. GetList();}}

Then in the browser access address: http://localhost:8080/myspringboot/score/scoreList test.

Finally, Spring will automatically create an implementation class for the interface that we inherit from the Crudrepository interface. We only need to use annotations @Autowired injection when we use it (there is no need to add annotations such as @Component, @Repository, etc. on the Iscoredao interface).
Also, I am here for the sake of simplicity, directly the operation of the database is used in the controller, the actual project is not recommended to do so, iscoredao the role of the database is persistent, we should also have a Service (such as Scoreservice) to invoke Iscoredao method, and then calls the method in the Service in the controller. The reason is because, our database access layer, is the interface definition method, the above annotation injected SQL and parameters, no specific code logic processing. If we want to perform logical processing either before or after SQL execution, only in the Service or controller (not recommended).
We do it strictly this way (the persistence layer is only related to SQL, with no logical processing through the interface definition), which is the ultimate persistence layer. The more stringent the normative system, in a way, the more conducive to code management and project code iterative development.

This article introduces JPA compared to the previous introduction about JDBC, the additional file works are:

When you are familiar with one of the persistent data methods, the others are similar.

Spring Boot JPA Connection Database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.