SpringBoot Starter series JPA mysql

  • 2020-06-15 09:09:45
  • OfStack

1. Preparation and establishment of ES1en-ES2en-ES3en-ES4en project

1, http: / / start. spring. io /

Enter ES15en-ES16en-ES17en-ES18en for A and Artifact
B. Check web under Web
Check C MYSQL under SQL

2. Import project spring-ES32en-ES33en-ES34en into Eclips

Extract shortcut project ES38en-ES39en-ES40en-ES41en to a folder

B, eclips file- > import- > Import Existing Maven Projects-- > Select Maven projects-- > finish import project

3. After the project is imported, the file structure is shown in the figure below

4. Create web folder under package com.example

5. Easy to test, spring-ES65en-ES66en-ES67en and configuration file ES69en.ES70en are introduced

HelloController code for


package com.example.web; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
@RestController 
public class HelloController { 
  protected static Logger logger=LoggerFactory.getLogger(HelloController.class); 
  @RequestMapping("/") 
  public String helloworld(){ 
    logger.debug(" access hello"); 
    return "Hello world!"; 
  } 
  @RequestMapping("/hello/{name}") 
  public String helloName(@PathVariable String name){ 
    logger.debug(" access helloName,Name={}",name); 
    return "Hello "+name; 
  } 
} 

logback. xml configured


<configuration>  
  <!-- %m Output information ,%p The level of logging ,%t The thread of ,%d The date of ,%c The full name of a class ,,,, -->  
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
    <encoder>  
      <pattern>%d %p (%file:%line\)- %m%n</pattern> 
      <charset>GBK</charset>  
    </encoder>  
  </appender>  
  <appender name="baselog"  
    class="ch.qos.logback.core.rolling.RollingFileAppender">  
    <File>log/base.log</File>  
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
      <fileNamePattern>log/base.log.%d.i%</fileNamePattern>  
      <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">  
        <!-- or whenever the file size reaches 64 MB -->  
        <maxFileSize>64 MB</maxFileSize>  
      </timeBasedFileNamingAndTriggeringPolicy>  
    </rollingPolicy>  
    <encoder>  
      <pattern>  
        %d %p (%file:%line\)- %m%n 
      </pattern>  
      <charset>UTF-8</charset> <!--  Set the character set here  -->  
    </encoder>  
  </appender>  
  <root level="info">  
    <appender-ref ref="STDOUT" />  
  </root>  
  <logger name="com.example" level="DEBUG">  
    <appender-ref ref="baselog" />  
  </logger>  
</configuration> 

Note: the logback. xml file is located under src/main/resources

6. Start the project and check the correctness through the browser

http://localhost:8080/

http: / / localhost: 8080 / hello/god

2. Use JPA to build business objects and access libraries

1. Create domain folder under package ES103en. example

2. Establish class Person in domain


package com.example.domain; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
@Entity 
public class Person { 
  @Id 
  @GeneratedValue 
  private Long id; 
  private String name; 
  private Integer age; 
  private String address; 
  public Person() { 
    super(); 
  } 
  public Person(Long id, String name, Integer age, String address) { 
    super(); 
    this.id = id; 
    this.name = name; 
    this.age = age; 
    this.address = address; 
  } 
  public Long getId() { 
    return id; 
  } 
  public void setId(Long id) { 
    this.id = id; 
  } 
  public String getName() { 
    return name; 
  } 
  public void setName(String name) { 
    this.name = name; 
  } 
  public Integer getAge() { 
    return age; 
  } 
  public void setAge(Integer age) { 
    this.age = age; 
  } 
  public String getAddress() { 
    return address; 
  } 
  public void setAddress(String address) { 
    this.address = address; 
  } 
} 

Note: Constructors

3. Create repository folder under package ES115en. example

4. Establish interface PersonRepository in repository


package com.example.repository; 
import java.util.List; 
import org.springframework.data.jpa.repository.JpaRepository; 
import org.springframework.data.jpa.repository.Query; 
import org.springframework.data.repository.query.Param; 
import org.springframework.stereotype.Repository; 
import com.example.domain.Person; 
@Repository 
public interface PersonRepository extends JpaRepository<Person,Long> { 
  List<Person> findByName(String name); 
  List<Person> findByAddress(String address); 
  List<Person> findByNameAndAddress(String name,String address); 
  @Query("select p from Person p where p.name=:name and p.address=:address") 
  List<Person> withNameAndAddressQuery(@Param("name")String Name,@Param("address")String address); 
} 

5. DataController was established in web


package com.example.web; 
import java.util.List; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.PageRequest; 
import org.springframework.data.domain.Sort; 
import org.springframework.data.domain.Sort.Direction; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
import com.example.domain.Person; 
import com.example.repository.PersonRepository; 
@RestController 
public class DataController { 
  protected static Logger logger=LoggerFactory.getLogger(DataController.class); 
  @Autowired 
  PersonRepository personRepository; 
  @RequestMapping("/save") 
  public Person save(String name,String address,Integer age){ 
    logger.debug("save  start "); 
    Person p=personRepository.save(new Person(null,name,age,address)); 
    logger.debug("save  The end of the "); 
    return p; 
  } 
  @RequestMapping("/q1") 
  public List<Person> q1(String address){ 
    logger.debug("q1  start "); 
    logger.debug("q1  Receive parameters address={}",address); 
    List<Person> people=personRepository.findByAddress(address); 
    return people; 
  } 
  @RequestMapping("/q2") 
  public List<Person> q2(String name,String address){ 
    logger.debug("q2  start "); 
    logger.debug("q2 Receive parameters name={},address={}",name,address); 
    return personRepository.findByNameAndAddress(name, address); 
  } 
  @RequestMapping("/q3") 
  public List<Person> q3(String name,String address){ 
    logger.debug("q3  start "); 
    logger.debug("q3 Receive parameters name={},address={}",name,address); 
    return personRepository.withNameAndAddressQuery(name, address); 
  } 
  @RequestMapping("/sort") 
  public List<Person> sort(){ 
    logger.debug("sort  start "); 
    List<Person> people=personRepository.findAll(new Sort(Direction.ASC,"age")); 
    return people; 
  } 
  @RequestMapping("/page") 
  public Page<Person> page(){ 
    logger.debug("page  start "); 
    Page<Person> people=personRepository.findAll(new PageRequest(1,2)); 
    return people; 
  } 
} 

6. Configure database connection under ES130en. properties (src/main/resources)


spring.datasource.url=jdbc:mysql://192.168.56.201:3306/bootsample?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true

7. Run the tests

Save the data first

http://localhost:8080/save?name=aa & & address = Beijing & & age=1
http://localhost:8080/save?name=ab & & address = Beijing & & age=2
http://localhost:8080/save?name=cq1 & & Chongqing address = & & age=50
http://localhost:8080/save?name=cq2 & & Chongqing address = & & age=51

B, query q1

http: / / localhost: 8080 / q1 & # 63; address = Beijing

C, query q2

http: / / localhost: 8080 / q2 & # 63; address = Beijing & & name=aa

D, query q3

http: / / localhost: 8080 / q3 & # 63; address = Beijing & & name=aa

E, sorting,

http://localhost:8080/sort

F, paging

http://localhost:8080/page

Using hibernate to access mysql is basically the same old technology, but using JPA simplifies the dao layer code, with little change for business objects.


Related articles: