Springboot Introduction (Idea article) (iii)

Source: Internet
Author: User

First, what is JPA

The JPA (Java persistence API) defines a set of criteria for object persistence, and the products that currently implement this specification are hibernate, TopLink, and so on.

Second, MySQL database example

1. Increase the configuration of database access in the Application.yml file

  

Ddl-auto: Optional attributes are available in the following categories.

  

Create a new table every time, then the data in the previous table will be discarded

A new table is created when the Update table does not exist, and is not created if it exists, so the original data is not lost

Create-drop each time a new table is created and the service is stopped, the created table is deleted

None to be known, is to do nothing, will not help you to build a table, can only use the existing table

Validate will validate the entity class and the table, and if the inconsistency will cause an error

2. New Entity class

  

 PackageCOM.ZMFX.JPA;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;Importjavax.persistence.Id; @Entity Public classDog {/*If these annotations are in a package, javax.persistence cannot be imported. May be a lack of dependency on the Javax persistence API that can be added to the POM*/@Id @GeneratedValuePrivateInteger ID;//numbering    PrivateInteger age;//Age    PrivateString name;//name     PublicDog () {} PublicDog (integer ID, integer age, String name) { This. ID =ID;  This. Age =Age ;  This. Name =name; }     PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicInteger getage () {returnAge ; }     Public voidsetage (Integer age) { This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}

3, write Repository interface class

Here we need to inherit the Jparepository class so that we can use the lower level to help us implement some good code

Equivalent to the persistence layer (the data access layer) we learned earlier to get the data in the database.

4, write Serivce layer

According to the policy pattern, we should have an interface and then correspond to the implementation class. Because the business here is relatively simple, we are not so troublesome. Maybe this layer I don't write below.

5. Write Controller layer

According to the access information, the corresponding business processing, page display.

Third, RestFul API

1, query all, FindAll () method of use. GET request

Repository Interface Class

 Package COM.ZMFX.JPA; Import org.springframework.data.jpa.repository.JpaRepository; /**  */Publicinterfaceextends jparepository<dog,integer> {} 

Controller layer

 PackageCOM.ZMFX.JPA;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.GetMapping;ImportOrg.springframework.web.bind.annotation.RestController;Importjava.util.List;/*** Control Layer*/@RestController Public classDogcontroller {//because the business is too simple, all of us omit the service layer and call the code of the data access layer directly@AutowiredPrivatedogrepository dogrepository; /*** Check all girls list *@return     */@GetMapping (Value= "/dogs")     PublicList<dog>doglist () {returnDogrepository.findall ();//FindAll () method is the bottom-level help me not to achieve good    }}

A software postman is recommended, which can simulate the HTTP access of the front-end, without writing the page

2, according to the ID query a record, the use of FindByID (), GET request

New code in Controller

/**      * The     specified dog @param id      is queried based on ID@return     *     / = "/dog/{id}")    public optional<dog> Finddogbyid (@PathVariable ("id ") Integer ID) {        return Dogrepository.findbyid (ID);   Note The return value of this method    }

Then, access using Postman, which is shown below:

  

3, add a Dog,save () method of use, POST request

New code in the controller layer

 /**   * Add a dog *   @param   age *   @param   name *   @return  */< /span> @PostMapping (value  = "/adddog"                       Span style= "COLOR: #0000ff" >public  Dog Adddog (@RequestParam ("Age"  "name" ) String name) {dog dog  =new   Dog ();        Dog.setage (age);        Dog.setname (name);     return   Dogrepository.save (dog); }

Then use the postman to visit, the display effect is as follows:

4, update the dog's information, the use of the Save () method, put request

Add the following code to the controller

/*** Update dog information *@paramID *@paramAge *@paramname *@return     */@PutMapping (Value= "Updatedog/{id}")     PublicDog Updatedog (@PathVariable ("id") Integer ID, @RequestParam ("Age") Integer Age, @RequestParam ("Name") (String name) {Dog dog=NewDog ();        Dog.setid (ID);        Dog.setname (name);        Dog.setage (age);        System.out.println (dog); returnDogrepository.save (dog);//Note that the Save () method is used, depending on the primary key, so the primary key cannot be changed}

Here, use Postman's put request and note the use of x-www-form-urlencoded for the parameter

The effect after the visit should be as follows:

5. Delete a record, Deletebyid () method, delete request

Add the following code to the controller:

/**      * Delete a     record @param  ID     *    /= "/del/{id}")     publicvoid Deldogbyid (@PathVariable ("id") Integer ID) {        Dogrepository.deletebyid (ID);    }

The Delette request is used in postman because there is no return value, so you need to see the effect in the database

6, according to the age to inquire, oneself in repository definition

The dogrepository becomes

 package   COM.ZMFX.JPA;  import   org.springframework.data.jpa.repository.JpaRepository;  import   java.util.List;  /**   * This interface needs to inherit an interface Jparepository * so you can use some of the common methods that are written for us on the ground floor  */ public  interface  Dogrepository extends  jparepository<dog,integer>  { //  search by age  list<dog> findbyage (Integer age); //  Note the format of the method name, findby+ property name.  }  

New code in Controller

/**      * search      by age */= "/dogs/{age}    ") Public List<dog > Doglist (@PathVariable ("Age"), Integer age)        {return  dogrepository.findbyage (age );    }

Then use postman to access it, showing the following:

  

Iv. Management of affairs

1. Before joining the transaction

Controller Layer Add code

// This involves transactions, so we join the service dependency     @Autowired    private  dogservice dogservice;     /**      * method      of transaction Test */    = "/dogs/tx") public void  txtest () {        System.out.println ("entered Controller");        Dogservice.addtwodog ();    }

Service layer code, where the transaction is used, so create a new Dogservice class

 PackageCOM.ZMFX.JPA;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service; @Service Public classDogservice {@AutowiredPrivatedogrepository dogrepository; /*** Add two records at the same time*/     Public voidAddtwodog () {//simulate two data linesDog dog1=NewDog (); Dog1.setage (2); Dog1.setname ("Little Black 1"); //simulate the second piece of dataDog dog2=NewDog (); Dog2.setage (2); Dog2.setname ("Little Black 2"); System.out.println ("entered the service."); //inserting data into a databaseDogrepository.save (DOG1); System.out.println (5/0);//simulating anomaliesDogrepository.save (DOG2); }}

Then using HTTP://127.0.0.1:8083/DEV/DOGS/TX for access, we found that the background throws an exception, but the database added the first record.

  

2. After joining the transaction

We'll be able to make the little black 1 and the Little Black 2 die.

The rest is unchanged, and then a @transactional annotation is added to the method that adds the transaction. That is, the service's public void Addtwodog () adds annotations

  

 PackageCOM.ZMFX.JPA;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;Importorg.springframework.transaction.annotation.Transactional; @Service Public classDogservice {@AutowiredPrivatedogrepository dogrepository; /*** Add two records at the same time*/@Transactional//Join Transaction Control     Public voidAddtwodog () {//simulate two data linesDog dog1=NewDog (); Dog1.setage (2); Dog1.setname ("Little Black 1"); //simulate the second piece of dataDog dog2=NewDog (); Dog2.setage (2); Dog2.setname ("Little Black 2"); System.out.println ("entered the service."); //inserting data into a databaseDogrepository.save (DOG1); System.out.println (5/0);//simulating anomaliesDogrepository.save (DOG2); }}

Then delete the database, small black 1 This record, restart the Springboot service, and visit Http://127.0.0.1:8083/dev/dogs/tx again.

Or the exception, and then go to the database, found that two records are not added. Transaction control added successfully.

   

Springboot Introduction (Idea article) (iii)

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.