SpringBoot is an upgrade to SpringMVC, which is easier for encoding, configuration, deployment and monitoring.
Microservices
Microservices is an emerging software architecture that splits a large single application and service into dozens of supported microservices. A microservice strategy can make work easier, which can scale a single component instead of an entire application stack, thus meeting service-level protocols.
Spring provides a complete set of components for microservices - SpringClound, and SpirngBoot is the basis.
The first SpringBoot program
The development software used here is IntelliJ Idea, which is not much different from Eclipse, with a cooler interface and more powerful functions; Android Studio is developed based on IntelliJ. I have used Android Studio before, and the interfaces of both of them are almost the same.
IntelliJ Idea official website: http://www.jetbrains.com/idea/
After configuring maven, tomcat, jdk, you can use it
The Alibaba Cloud image of the central warehouse configured by maven, the speed of downloading jar packages at this address, who knows who uses it!
setting.xml
.. <mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> . .
Create SpringBoot Projects with IDEA
My IDEA version: IntelliJ IDEA 2016.3.1
The project structure is:
The default maven pom.xml file for the project
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jxust</groupId> <artifactId>spirngbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spirngbootdemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
Run the main method of SpirngbootdemoApplication and you can start running.
For other startup methods, please see the video tutorial http://www.imooc.com/learn/767/
Console output:
"C:/Program Files/Java/jdk1.8.0_91/bin/java" .... . ____ __ __ /// ___'_ __ __ _(_)_ ___ __ / / / / / ( ( )/___ | '_ | '_| | / / / / / / / / / / / / / / / / | | | | | | | | | | | | || (_| | ) ) ) ) ' |____| .__|| |_| |_| |_/__, | / / / / / ==================================____/=/_/_/ :: Spring Boot :: (v1.4.2.RELEASE) 2016-12-16 14:56:52.083 INFO 15872 --- [ main] osjeaAnnotationMBeanExporter : Registering beans for JMX exposure on startup2016-12-16 14:56:52.215 INFO 15872 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-12-16 14:56:52.255 INFO 15872 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-12-16 14:56:52.255 INFO 15872 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-12-16 14:56:52.255 INFO 15872 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-12-16 14:56:52.255 INFO 15872 --- [ main] com.jxust.SpirngbootdemoApplication : Started SpirngbootdemoApplication in 7.795 seconds (JVM running for 9.177)
From here you can see the port number of Tomcat. Since there is no custom controller, there is no view yet. Let’s create a view that outputs Hello SpringBoot!.
Create a HelloController, located under the controller package
HelloController.java
package com.jxust.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;/** * Created by Peng * Time: 2016/12/16 15:45 */@RestControllerpublic class HelloController { @RequestMapping("/hello") public String says(){ return "Hello SpringBoot!"; }}@RestController New annotation after Spring4. It turns out that returning json requires @ResponseBody to cooperate with @Controller. Now one is the best two
Enter http://localhost:8080/hello in the browser to output the sentence Hello SpringBoot!
Custom property configuration
The application.properties file is used
Configure port number and access prefix
application.propertiesserver.port=8081server.context-path=/springboot
In addition to using .properties format files, you can also use .yml format configuration files (recommended), which is easier
application.yml
Delete the original application.properties file
Pay attention to the format, spaces cannot be missing
Get the attribute value in the configuration file
We can also configure data in the configuration file and obtain it in the Controller, for example:
application.yml
server: port: 8081 context-path: /springbootname: Xiaopang
HelloController Gets the value in the configuration file
HelloController.java
....@RestControllerpublic class HelloController { @Value("${name}") private String name; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String says(){ return name; }} The returned value of name
Diversification of value configuration methods in configuration files
The values of the configuration file can be multiple or combined, such as:
application.yml
name: Xiaopang age: 22 or name: Xiaopang age: 22content: "name: ${name},age: ${age}" or server: port: 8081 context-path: /springbootperson: name: Xiaopang age: 22The first two configurations are the same way to get values, but for this method, person has two corresponding properties, which need to be handled in this way.
PersonProperties.java
package com.jxust;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * Created by Peng * Time: 2016/12/16 16:34 */@Component@ConfigurationProperties(prefix = "person")public class PersonProperties { private String name; private Integer age; 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; }}Alt+insert shortcut key prompts to generate Getter and Setter
pom.xml needs to add the following dependencies to handle warnings
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional></dependency>
HelloController.java
package com.jxust.controller;import com.jxust.PersonProperties;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * Created by Peng * Time: 2016/12/15 20:55 */@RestControllerpublic class HelloController { @Autowired private PersonProperties personProperties; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String says(){ return personProperties.getName()+personProperties.getAge(); }}About the configuration file application.yml multiple sets of configurations
Similar to the internationalization of il8n files, i18n_en_US.properties and i18n_zh_CN.properties
This can solve the embarrassment of frequent configuration modifications
It is up to the application.yml configuration file to decide which configuration file to use.
application.yml
spring: profiles: active: a
application-a.yml
server: port: 8081 context-path: /springbootperson: name: Xiaoleiage: 21
application-b.yml
server: port: 8081 context-path: /springbootperson: name: Xiaopang age: 22
SpringBoot adds, deletes, and changes to check examples
Complete project structure
Controller usage
Controller usage
@Controller chu handles http request
@RestController New annotation after Spring4, it turns out that returning json requires @ResponseBody to cooperate with @Controller
@RequestMapping Configure url mapping
Requests for REST style
For annotations on methods in Controller
@RequestMapping(value = "/hello",method = RequestMethod.GET) @RequestMapping(value = "/hello",method = RequestMethod.POST) @RequestMapping(value = "/hello",method = RequestMethod.DELETE) @RequestMapping(value = "/hello",method = RequestMethod.PUT)
SpringBoot simplifies the above annotation
@GetMapping(value = "/girls") @PostMapping(value = "/girls") @PutMapping(value = "/girls/{id}") @DeleteMapping(value = "/girls/{id}")The browser needs to send requests in different ways, and you can install the HttpRequester plug-in, and Firefox Browser can directly search for this component to install.
spring-data-jpa
JPA full name Java Persistence API.JPA describes the mapping relationship of an object-relationship table through JDK 5.0 annotation or XML, and persists the running entity objects into the database.
Hibernate3.2+, TopLink 10.1.3 and OpenJPA all provide JPA implementation.
Create a MySQL database using JPA
pom.xml adds JPA and MySQL dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
Configuring JPA and database
application.yml
spring: profiles: active: a datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/db_person username: root password: root jpa: hibernate: ddl-auto: update show-sql: true
Format is important
You need to create the db_person database manually
Create a Person entity class corresponding to the data table
Person.java
package com.jxust.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;/** * Created by Peng * Time: 2016/12/16 17:56 */@Entitypublic class Person { @Id @GeneratedValue private Integer id; private String name; private Integer age; //The constructor must be public Person() { } public Integer getId() { return id; } public void setId(Integer 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; }}After running the project, check the database and the table person will be automatically created
mysql> use db_person;Database changedmysql> desc person;+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | NULL | |+------------------------+---------+----------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Next, you can add, delete, modify and check the person table
Create controller PersonController.java
First create an interface PersonRepository, located under the dao package. PersonController calls the method inherited from JpaRepository to achieve interaction with the database.
The function of this PersonRepository interface is similar to the interface function of the dao layer in the SSM framework; in the SSM framework, the Service layer indirectly executes the corresponding SQL statements in the Mybatis database mapping file (.xml) through this interface, and performs the operations of adding, deleting, modifying and searching the database. (Mapper automatically implements DAO interface)
PersonRepository.java
package com.jxust.dao;import com.jxust.entity.Person;import org.springframework.data.jpa.repository.JpaRepository;/** * Created by Peng * Time: 2016/12/16 18:07 */public interface PersonRepository extends JpaRepository<Person,Integer> {}PersonController.java
package com.jxust.controller;import com.jxust.dao.PersonRepository;import com.jxust.entity.Person;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * Created by Peng * Time: 2016/12/16 18:04 */@RestControllerpublic class PersonController { @Autowired PersonRepository personRepository; @GetMapping(value = "/person") private List<Person> personList() { return personRepository.findAll(); }}Add two pieces of data to the database
mysql> select * from person;+---+-----+------+| id | age | name |+----+-------+-------+| 1 | 23 | Charlotte || 2 | 21 | Ma Dongmei |+----+-------+------+2 rows in set (0.04 sec)
Start the project execution request http://localhost:8081/springboot/person
SQL statements output by the console:
Hibernate: select person0_.id as id1_0_, person0_.age as age2_0_, person0_.name as name3_0_ from person person0_
Other methods of adding, deleting, modifying and checking
PersonController.java
.... /** * Add a person* * @param name * @param age * @return */ @PostMapping(value = "/person") public Person personAdd(@RequestParam("name") String name, @RequestParam("age") Integer age) { Person person = new Person(); person.setName(name); person.setAge(age); return personRepository.save(person); } /** * Query a person* * @param id * @return */ @GetMapping(value = "/person/{id}") public Person personFindOne(@PathVariable("id") Integer id) { return personRepository.findOne(id); } /** * Delete a person* * @param id */ @DeleteMapping(value = "/person/{id}") public void personDelete(@PathVariable("id") Integer id) { personRepository.delete(id); } /** * Update a person* * @param id * @param name * @param age * @return */ @PutMapping(value = "/person/{id}") public Person personUpdate(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age) { Person person = new Person(); person.setId(id); person.setName(name); person.setAge(age); return personRepository.save(person); }The corresponding request method is:
Query a user:
Add a user
Delete a user (no return value)
Update a user
So, can I check based on age? The answer is that it's not possible yet
From the console statements, it can be seen that the SQL statements are queried based on id
Hibernate: select person0_.id as id1_0_0_, person0_.age as age2_0_0_, person0_.name as name3_0_0_ from person person0_ where person0_.id=?
Query by age
Add a method to PersonRepository findByAge(Integer age)
public interface PersonRepository extends JpaRepository<Person,Integer> { /** * Query by age* Method name fixed findByAge * @param age * @return */ public List<Person> findByAge(Integer age);}Add corresponding query method to PersonController
.... /** * Query by age* @param age * @return */ @GetMapping(value = "/person/age/{age}") public List<Person> personListByAge(@PathVariable("age") Integer age) { return personRepository.findByAge(age); }Enter the request http://localhost:8081/springboot/person/age/23 to query the person with age 23
The console outputs SQL statement:
Hibernate: select person0_.id as id1_0_, person0_.age as age2_0_, person0_.name as name3_0_ from person person0_ where person0_.age=?
Transaction Management
Two SQL statements are executed in one method at the same time. In order to prevent one SQL statement from successfully executing and the other SQL statement from failing, transaction management is introduced. @Transactional transaction annotation is required to add the method.
Transactions ensure the integrity and consistency of database data
PersonService.java
In PersonControll
package com.jxust.service;import com.jxust.dao.PersonRepository;import com.jxust.entity.Person;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import javax.transaction.Transactional;/** * Created by Peng * Time: 2016/12/16 19:30 */@Servicepublic class PersonService { @Autowired private PersonRepository personRepository; /** * Transaction management test* Two pieces of data succeed at the same time, or are not successful at the same time* Ensure the integrity and consistency of database data*/ @Transactional public void insertTwo(){ Person personA = new Person(); personA.setName("Qiuya"); personA.setAge(19); personRepository.save(personA); System.out.print(1/0); Person personB = new Person(); personB.setName("Mengtejiao"); personB.setAge(25); personRepository.save(personB); }}Test in er
... @Autowired private PersonService personService; ... /** * Transaction test*/ @PostMapping("/person/two") public void personTwo(){ personService.insertTwo(); }Rerun the project and execute the request post method http://localhost:8081/springboot/person/two
The first piece of data was not added to the database, indicating that there is transaction management
Complete PersonController.java, PersonRepository.java and pom.xml
PersonController.java
package com.jxust.controller;import com.jxust.dao.PersonRepository;import com.jxust.entity.Person;import com.jxust.service.PersonService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;/** * Created by Peng * Time: 2016/12/16 18:04 */@RestControllerpublic class PersonController { @Autowired PersonRepository personRepository; @Autowired private PersonService personService; /** * Query the list of all personnel* * @return */ @GetMapping(value = "/person") private List<Person> personList() { return personRepository.findAll(); } /** * Add a person* * @param name * @param age * @return */ @PostMapping(value = "/person") public Person personAdd(@RequestParam("name") String name, @RequestParam("age") Integer age) { Person person = new Person(); person.setName(name); person.setAge(age); return personRepository.save(person); } /** * Query a person* * @param id * @return */ @GetMapping(value = "/person/{id}") public Person personFindOne(@PathVariable("id") Integer id) { return personRepository.findOne(id); } /** * Delete a person* * @param id */ @DeleteMapping(value = "/person/{id}") public void personDelete(@PathVariable("id") Integer id) { personRepository.delete(id); } /** * Update a person* * @param id * @param name * @param age * @return */ @PutMapping(value = "/person/{id}") public Person personUpdate(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age) { Person person = new Person(); person.setId(id); person.setName(name); person.setAge(age); return personRepository.save(person); } /** * Query by age* @param age * @return */ @GetMapping(value = "/person/age/{age}") public List<Person> personListByAge(@PathVariable("age") Integer age) { return personRepository.findByAge(age); } /** * Transaction test*/ @PostMapping("/person/two") public void personTwo(){ personService.insertTwo(); }}PersonRepository.java
package com.jxust.dao;import com.jxust.entity.Person;import org.springframework.data.jpa.repository.JpaRepository;import java.util.List;/** * Created by Peng * Time: 2016/12/16 18:07 */public interface PersonRepository extends JpaRepository<Person,Integer> { /** * Query by age* Method name fixed* @param age * @return */ public List<Person> findByAge(Integer age);}pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jxust</groupId> <artifactId>spirngbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spirngbootdemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependency> </dependency> </build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
Summarize
The above is a detailed explanation of the IntelliJ Idea SpringBoot database addition, deletion, modification and search examples introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!