Spring-boot official case analysis of the DATA-JPA

Source: Internet
Author: User

Spring-boot official case analysis of the DATA-JPA


Package SAMPLE.DATA.JPA;

Import Org.junit.Before;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.boot.test.SpringApplicationConfiguration;
Import Org.springframework.test.context.ActiveProfiles;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Import org.springframework.test.context.web.WebAppConfiguration;
Import ORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;
Import Org.springframework.test.web.servlet.setup.MockMvcBuilders;
Import Org.springframework.web.context.WebApplicationContext;

Import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Integration test to run theapplication.
*
* @author Olivergierke
*/
@RunWith (Springjunit4classrunner.class)
@SpringApplicationConfiguration (classes = sampledatajpaapplication.class)
@WebAppConfiguration
@ActiveProfiles ("Scratch")
Separate profile for Web tests to avoid clashing databases
public class Sampledatajpaapplicationtests {

@Autowired
Private Webapplicationcontextcontext;

Private MOCKMVC MVC;

@Before
public void SetUp () {
THIS.MVC = Mockmvcbuilders.webappcontextsetup (this.context). build ();
}

@Test
public void Testhome () throws exception{

This.mvc.perform (Get ("/")). Andexpect (Status (). IsOk ())
. Andexpect (Content (). String ("Bath"));
}
}

    1. First, the configuration file that you want to use is selected in the test class

@ActiveProfiles ("Scratch")

The corresponding properties are application-scratch.properties

The contents are:

Spring.datasource.url:jdbc:hsqldb:mem:scratchdb

Defines the URL of the data source;

@Autowired
Private Webapplicationcontext context;

Inject application context contexts;

Define MOCKMVC and then @before annotations to execute the initialization container

@Before
public void SetUp () {

THIS.MVC = Mockmvcbuilders.webappcontextsetup (this.context). build ();
}

Then the simulation sends the request test:

Class Diagram Relationships:

Follow this test case to go through the request processing process:

This.mvc.perform (Get ("/")). Andexpect (Status (). IsOk ())
. Andexpect (Content (). String ("Bath"));

GET request processing: to Samplecontroller

@Autowired
Private Cityservice Cityservice;

@RequestMapping ("/")
@ResponseBody
@Transactional (readOnly = True)
Public String HelloWorld () {
Return this.cityService.getCity ("Bath", "UK"). GetName ();
}
}

The Cityservice component property is injected and the transaction type is read-only.

Then execute the getcity () method in the service component Cityservice;

and pass in the parameter Name= "Bath", country= "UK", and then call the GetName method to get the name value.

Public interface Cityservice {

Page<city> findcities (Citysearchcriteria criteria, pageable pageable);

City getcity (string name, String country);

Page
}

The query method is defined in the interface.

The return value exists in the Page object

In the implementation class, mark as component and set Id=cityservice, so that the program execution will find the Impl class;


@Component ("Cityservice")
@Transactional
Class Cityserviceimpl implements Cityservice {

Private final cityrepository cityrepository;

Private final hotelrepository hotelrepository;

@Autowired
Public Cityserviceimpl (Cityrepository cityrepository, hotelrepository hotelrepository) {
This.cityrepository = cityrepository;
This.hotelrepository = hotelrepository;
}

@Override
Public page<city> findcities (citysearchcriteria criteria, pageable pageable) {

Assert.notnull (criteria, "criteria must not being null");
String name = Criteria.getname ();

if (! Stringutils.haslength (name)) {
return this.cityRepository.findAll (NULL);
}

String country = "";
int splitpos = Name.lastindexof (",");

if (splitpos >= 0) {
Country = name.substring (Splitpos + 1);
Name = name.substring (0, Splitpos);
}

Return this.cityrepository
. Findbynamecontainingandcountrycontainingallignoringcase (Name.trim (),
Country.trim (), pageable);
}

@Override
Public City Getcity (string name, String country) {
Assert.notnull (name, "name must not is null");
Assert.notnull (country, "country must not being null");
Return This.cityRepository.findByNameAndCountryAllIgnoringCase (name, country);
}

@Override
Public pageAssert.notnull (city, "City must not being null");
Return this.hotelRepository.findByCity (city, pageable);
}
}
Because a transactional operation is performed, add @transactional

Inject other components through a constructor function;


@Override
Public City Getcity (string name, String country) {
Assert.notnull (name, "name must not is null");
Assert.notnull (country, "country must not being null");
Return This.cityRepository.findByNameAndCountryAllIgnoringCase (name, country);
}

In this method, the assertion determines whether it is empty, then executes the DAO query, and in JPA, the method name is defined in the interface by different keywords to map to the SQL query statement, the above method is equivalent to the SELECT * from the city C where name= "bath" Returns a city object, provided that the name value is uniquely determined.

Spring-boot official case analysis of the DATA-JPA

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.