IntelliJ idea Springboot Database additions and Deletions example

Source: Internet
Author: User
Tags bind json xmlns mysql database port number tomcat aliyun
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ))
  '  |____|. __|_| |_|_| |_\__, |////
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot::        (V1.4.2.release)

Reference Tutorial : http://www.imooc.com/learn/767\ springboot

Springboot is an upgraded version of SPRINGMVC, which makes it simpler to service than coding, configuration, deployment, and monitoring

MicroServices are an emerging software architecture that splits a large single application and service into dozens of support microservices . A microservices strategy can make work easier, and it can extend a single component rather than the entire application stack to meet service level agreements.

Spring provides a complete set of component-springclound for MicroServices, and Spirngboot is the foundation.

First Springboot program

The development software used here is IntelliJ idea, and Eclipse is not too much, the interface is more cool, more powerful, Android Studio is based on IntelliJ development, I have used Android studio, it is almost the same interface.

IntelliJ Idea Website: http://www.jetbrains.com/idea/
Configure MAVEN, Tomcat, JDK to use the MAVEN- configured central repository Alibaba cloud image

This address downloads the speed of the jar package, who knows with whom.

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>
  </mirrors>
  .
  
Create a Springboot project using idea

My idea version: IntelliJ idea 2016.3.1

The project structure is:

Project default maven Pom.xml file

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.jxus T</groupid> <artifactId>spirngbootdemo</artifactId> <version>0.0.1-snapshot</version&
    Gt <packaging>jar</packaging> <name>spirngbootdemo</name> <description>demo Project fo
        R 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> &lt
            ;d ependencies> <dependency> <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-TEST&L t;/artifactid> <scope>test</scope> </dependency> </dependencies> & lt;build> <plugins> <plugin> <groupid>org.springframework.boot&lt
        ;/groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </proJect> 

Run the main method of Spirngbootdemoapplication to start running.

For other start-up methods, 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] O.s.j.e.a.annotationmbeanexporter        : Registering beans for JMX exposure on startup
2016-12-16 14:56:52.215  INFO 15872---[           main] S.b.c.e.t.tomcatembeddedservletcontainer: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, because there is no custom controller, so there is no view, below to create a view of the output 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 */
@RestController Public
class Hellocontroller {

    @RequestMapping ("/hello") public
    String say () {
        return "Hello springboot!";
    }
}

@RestController Spring4 after the newly added annotations, the original return JSON needs @responsebody mate @controller, now a top two

Enter Http://localhost:8080/hello in the browser to output the Hello springboot! sentence.

Custom Property Configuration

It's application.properties this file.

configuring port numbers and access prefixes

Application.properties

server.port=8081
Server.context-path=/springboot

In addition to using the. properties format file, you can also use the. yml format configuration file (recommended) for easier
Application.yml

Delete the original application.properties file
Note the format, space can not be less Get property values in a configuration file

We can also configure the data in the configuration file and get it in the Controller, for example:
Application.yml

Server:
  port:8081
  context-path:/springboot
Name: Chubby

Hellocontroller getting the values in the configuration file

Hellocontroller.java

....
@RestController public
class Hellocontroller {

    @Value ("${name}")
    private String name;

    @RequestMapping (value = "/hello", method = requestmethod.get) public
    String say () {
        return name;
    }
}

The value returned as a name

diversification of the way values are configured in the configuration file

The value of a configuration file can be multiple, or it can be a combination, such as: application.yml

Name: Chubby
age:22

or APPLICATION.YML.

Name: Chubby
age:22
content: "Name: ${name},age: ${age}"

or APPLICATION.YML.

Server:
  port:8081
  context-path:/springboot person
:
  name: Chubby
  age:22

The first two configurations get values the same way, but for this way, the person has a corresponding two attributes that need to be handled

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 prompt generates Getter and Setter

Pom.xml need to add the following dependencies to handle the warning

<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 */
@RestController Public
class Hellocontroller { c11/> @Autowired
   private personproperties personproperties;

    @RequestMapping (value = "/hello", method = requestmethod.get) public
    String say () {
        return Personproperties.getname () +personproperties.getage ();
    }
}

about configuring multiple sets of configuration file Application.yml

Similar il8n file internationalization configuration methods I18n_en_us.properties and I18n_zh_cn.properties
This solves the awkward need to frequently modify the configuration

It is up to the APPLICATION.YML configuration file to use that set of profiles.

Application.yml

Spring:
  Profiles:
    active:a

Application-a.yml

Server:
  port:8081
  context-path:/springboot person
:
  name: Ray
  age:21

Application-b.yml

Server:
  port:8081
  context-path:/springboot person
:
  name: Chubby
  age:22
springboot Additions and deletions to verify examples The complete project structure

Use of Controller

@Controller Chu handles HTTP requests

@RestController SPRING4 new annotations, originally returning JSON requires @responsebody mates @controller

@ requestmapping Configuring URL Mappings

For REST-style requests

For annotations on methods in a 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 annotations.

@GetMapping (value = "/girls")
@PostMapping (value = "/girls")
@PutMapping (value = "/girls/{id}")
@ DeleteMapping (value = "/girls/{id}")

Browsers need to send different ways to request, you can install the Httprequester plug-in, Firefox can directly search for the component installation.

SPRING-DATA-JPA

JPA Full name Java Persistence API. JPA describes the mapping of objects-relational tables through JDK 5.0 annotations or XML, and persists entity objects for the run-time into the database.

hibernate3.2+, TopLink 10.1.3, and OPENJPA all provide JPA implementations. create a MySQL database with JPA

Pom.xml joins 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 Databases

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 manually create a Db_person database to create the entity class corresponding to the data table person

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 */@Entity public class Person {@Id @GeneratedValue private
    Integer ID;
    private String name;

    Private Integer age;
    The constructor public must have a 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</

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.