Spring Boot JPA Connection Database

Source: Internet
Author: User

This article describes how to include JPA as a persistence method in spring Boot project.

Change Pom.xml Dependency

Unlike the one described in the previous article, the SPRING-BOOT-STARTER-JDBC change to SPRING-BOOT-STARTER-DATA-JPA is possible. Of course, the database driver package is also indispensable. For example, the following:

 <!--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: Assuming that you want JDBC and JPA to work together, Spring Boot is supported, and you just need to add JDBC and JPA dependencies to the Pom.xml. No additional special processing is required, see the "Spring-boot JDBC Connection database" for a description of the use of JDBC.

To change the property configuration file

It is not necessary to include JPA-related attributes in the attribute configuration file. We assume that Url\username\password\driver-class-name, which joins DataSource only, can be used normally, and that other JPA configurations are optional.

Spring. JPA. Database=spring. JPA. Show-sql=spring. JPA. Properties=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=

Familiarity with JPA's basis names should basically be known about the effects of these distinctions.

Traditionally. JPA entity classes are specified in the Persistence.xml file. Use Spring Boot. This file is not necessary. Because it uses "entity scan". By default, all packages under the master configuration @EnableAutoConfiguration or @SpringBootApplication will be scanned. @Embeddable or @MappedSuperclass classes are managed, regardless of the use of annotations @Entity.

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 changes, 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")//Say here, when I use the specified database column. Using lowercase will not work and changing to uppercase will be fine.

不知道为何。假设遇到一样问题的能够尝试下。 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; // 省去get、set 方法(占用文章空间)}

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 visit the browser address: http://localhost:8080/myspringboot/score/scoreList test.

Finally, Spring will take its own initiative to create an implementation class for the interface that we inherit from the Crudrepository interface. We simply need to use annotations @Autowired injection when we use them (there is no need to add annotations such as @Component, @Repository, and so on on the Iscoredao interface).


Also, I'm here for the sake of simplicity. It is not recommended to use the operations database directly in the controller, in the actual project. The Iscoredao role is a database persistence, and we should also have a Service (such as Scoreservice) to invoke the Iscoredao method. The methods in the Service are then called in the controller.

The reason is because. Our database access layer. Are interface definition methods, the above annotations inject SQL and parameters, no specific code logic processing. Suppose we want to run logical processing before or after running SQL, only in the Service or controller (not recommended).
We do it strictly in 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 some ways, the more beneficial the code management and the iterative development of the project code.

Of course, suppose you really want to implement your class implementation classes. The following is an example code to be attached before this. Let's look at a picture first:

This figure is the interface instance that spring creates with the dynamic proxy. It can be seen that it uses the Simplejparepository class, so suppose we implement our own Repository. The ability to expand simplejparepository and achieve your own factory-class start. There is no specific explanation here. Note that all implementations of the Repository interface do not need to add @Repository annotations, or you will encounter problems.

This article describes JPA compared to the previous introduction about JDBC, adding files to project:

Familiar with one of the methods of persistent data, other similarities 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.