Application of Spring Data JPA in spring boot

Source: Internet
Author: User
Tags dateformat

1.JPA

JPA (Java Persistence API) is the Java Persistence specification proposed by Sun. It provides Java developers with an object/association mapping tool to manage relational data in Java applications. The main purpose of his presence is to simplify existing persistent development efforts and integrate ORM technology, and to end the current Hibernate,toplink,jdo and other ORM frameworks for each battalion. It is worth noting that JPA is developed on the basis of fully absorbing the existing HIBERNATE,TOPLINK,JDO and other ORM frameworks, with the advantages of ease of use and strong scalability. JPA is a set of specifications, not a set of products, then like hibernate,toplink,jdo they are a set of products, if these products implement the JPA specification, then we can call them to implement the JPA product.

2. Project Construction

This paper uses idea to build the JPA application of Spring boot, the demo structure is as follows:

3. Concrete implementation

(1) configuration file

    • Pom.xml joins the SPRING-BOOT-STARTER-DATA-JPA and Mysql-connector-java dependencies as shown below.
<Dependency>    <groupId>Org.springframework.boot</groupId>    <Artifactid>Spring-boot-starter-data-jpa</Artifactid></Dependency><Dependency>    <groupId>Mysql</groupId>    <Artifactid>Mysql-connector-java</Artifactid>    <version>6.0.6</version></Dependency>
    • Application.yml add Hibernate, JPA configuration, and return JSON to the date field of the special processing configuration, note that the Time-zone settings must be consistent with the URL configuration of MySQL, otherwise it will cause a time difference of 8 hours. JPA show-sql function, if set to true, after executing the program can see the SQL statement in the console, as shown below.
Spring:  profiles:    active:product  datasource:    driver-class-name:com.mysql.cj.jdbc.driver    url:jdbc:mysql://localhost:3306/saascrm?useunicode=true&characterencoding=utf-8&usessl=true& SERVERTIMEZONE=UTC    username:root    password:snail123  JPA:    hibernate:      Ddl-auto: Update    show-sql:true  Jackson:    date-format:yyyy-mm-dd HH:mm:ss    TIME-ZONE:UTC

(2) layering

In order to differentiate the various modules, set up several packages for the project: Controller, Entity, respository, service, this is a typical MVC architecture, the representative meaning of each level will not be mentioned here.

(3) Respository layer

Spring data JPA frees us from the operations of the DAO layer, and basically all crud can be relied upon to implement the Jparepository interface

 Public Interface Userrepository extends jparepository<userinfo,long> {}

(4) Entity layer

Defines the user Information table entity UserInfo, which is mapped to the database through hibernate, as follows:

@Entity @component Public classUserInfo { PublicUserInfo () {} @Id @GeneratedValue PublicLong getId () {returnID; }     Public voidsetId (Long id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getjobnumber () {returnJobnumber; }     Public voidSetjobnumber (String jobnumber) { This. Jobnumber =Jobnumber; }     PublicDate Getcreatetime () {returnCreatetime; }     Public voidsetcreatetime (Date createtime) { This. Createtime =Createtime; }    PrivateLong ID;//ID    PrivateString name;//name    PrivateString Jobnumber;//Work No.    PrivateDate Createtime;//creation Time}

(5) Service layer

Defines the service layer interface and the service layer interface implementation class, as follows:

    • Userservice.java
 Public Interface userservice {    List<UserInfo> getuserlist ();    UserInfo getuserbyname (String name);    UserInfo Adduserinfo (UserInfo UserInfo);    UserInfo Updateuserinfobyid (UserInfo UserInfo);     void Deleteuserinfobyid (Long Id);    List<UserInfo>getcurrentuserlist ();    Page<UserInfo> getpageuserlist ();}
    • Userserviceimpl.java

Which involves a single table of additions and deletions, as well as paging queries, etc.

@Service Public classUserserviceimplImplementsuserservice{@AutowiredPrivateuserrepository userrepository; /*** Get a list of all users *@return     */     PublicList<userinfo>getuserlist () {List<UserInfo> userlist=NewArraylist<userinfo>(); UserList=Userrepository.findall (); returnuserlist; }    /*** Get user information by name *@paramName User name *@return     */     PublicUserInfo getuserbyname (String name) {returnuserrepository.findbyname (name); }    /*** New User information *@paramuserInfo User Information *@return     */     PublicUserInfo adduserinfo (UserInfo UserInfo) {returnUserrepository.save (UserInfo); }    /*** Update user information *@paramuserInfo User Information *@return     */     PublicUserInfo Updateuserinfobyid (UserInfo UserInfo) {returnUserrepository.save (UserInfo); }    /*** Delete User information *@paramID primary Key ID*/     Public voidDeleteuserinfobyid (Long id) {userrepository.delete (ID); }    /*** Get the latest user *@return     */     PublicList<userinfo>getcurrentuserlist () {sort sort=NewSort (Sort.Direction.DESC, "Createtime"); returnUserrepository.findall (sort); }    /*** Get paged users *@return     */     PublicPage<userinfo>getpageuserlist () {sort sort=NewSort (Sort.Direction.DESC, "Createtime"); pageable pageable=NewPagerequest (0,5, sort); returnUserrepository.findall (pageable); }}

(6) Controller layer

The date format needs to be converted, using SPRINGMVC annotations @initbinder and Spring's Webdatebinder classes in a controller that requires a date conversion. Webdatabinder is used to bind the request parameter to the specified property editor. Since the value of the foreground to the controller is of type string, if this property of set is an object when set to the model, spring will find the corresponding editor to convert, but And then set it in.

@RestController @requestmapping (value= "/test") Public classTestController {@AutowiredPrivateUserInfo UserInfo; @ResourcePrivateUserService UserService; /*** Get all Users *@return     */@GetMapping (Value= "/getuserlist")     PublicList<userinfo>getuserlist () {returnuserservice.getuserlist (); } @GetMapping (Value= "/getuserinfo")     PublicUserInfo Getuserinfobyname (@RequestParam ("name") (String name) {returnuserservice.getuserbyname (name); } @GetMapping (Value= "/getcurrentuserlist")     PublicList<userinfo>getcurrentuserlist () {returnuserservice.getcurrentuserlist (); } @GetMapping (Value= "/getpageuserlist")     PublicPage<userinfo>getpageuserlist () {returnuserservice.getpageuserlist (); } @PutMapping (Value= "/adduserinfo")     PublicUserInfo adduserinfo (UserInfo UserInfo) {returnUserservice.adduserinfo (UserInfo); } @PostMapping (Value= "/updateuserinfo")     PublicUserInfo updateuserinfo (UserInfo UserInfo) {returnUserservice.updateuserinfobyid (UserInfo); } @PostMapping (Value= "/deleteuserinfo")     Public voidDeleteuserinfo (@RequestParam ("id"Long ID) {Userservice.deleteuserinfobyid (ID); } @InitBinderprotected voidInit (httpservletrequest request, Servletrequestdatabinder Binder) {SimpleDateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Dateformat.settimezone (Timezone.gettimezone ("UTC"));/*timezone time zone, solve the problem of 8 hours difference*/binder.registercustomeditor (Date.class,NewCustomdateeditor (DateFormat,false)); }

4. Testing

HTTP defines different ways to interact with the server, with 4 basic methods, namely get,post,put,delete. URL full name is a resource descriptor, we can think: a URL address, which is used to describe a network of resources, and HTTP get,post,put,delete corresponding to this resource, change, increase, delete 4 operations.

This article is tested with the Postman tool, as shown in. (Note that if you choose the put request, you can only select x-www-form-urlencoded)

Application of Spring Data JPA in spring boot

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.