原文链接:http://www.dubby.cn/detail.html?id=9041

1.我们要做什么

本文介绍如果使用Spring + JPA来实现最简单的MySQL访问的web应用。

2.你需要什么

  • MySQL 5.6或者更高版本
  • 大约15分钟
  • 一个最爱的编辑器或者IDE
  • JDK 1.8 +
  • Maven 3.0+

3.创建项目

3.1 项目结构

maven项目,结构如下:

└── src
    └── main
        └── java
            └── hello

3.2 项目依赖

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>org.springframework</groupId>
    <artifactId>access-mysql-data</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Use MySQL Connector-J -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

spring-boot-maven-plugin的作用在[Spring系列——RESTful的web项目](http://www.dubby.cn/detail.html?id=9040#3.1 maven依赖)中说过了,在此不赘述。

3.3 准备数据库

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(250) DEFAULT NULL,
  `email` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

其实不创建这个表的,因为Spring有个选项可以自动创建,不过生产使用的时候不太可能那么干,所以这里还是写出DDL吧。

3.4 application.properties

Spring给你设置了所有默认值,数据库默认是H2,所以,如果你希望用MySQL,那么你需要自己定义数据库连接信息。

src/main/resources/application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password

想必你也知道,这个配置文件里的密码和用户名需要改成你的

spring.jpa.hibernate.ddl-auto可以取值为none, update, create, create-drop

  • none:这个选项下,应用不会更改MySQL数据库的结构。
  • update:Hibernate会根据实体类的结构来更改数据库的表结构。
  • create:每次连接到数据库的时候(应用程序运行起来的时候)都会重新创建表,但是关闭连接时(应用程序关闭的时候)不会删除表
  • create-drop:每次连接到数据库的时候(应用程序运行起来的时候)都会重新创建表,但是关闭连接时(应用程序关闭的时候)会删除表

对于H2这种集成的数据库,默认策略是create-drop,但是对于MySQL这种,默认策略是none

3.5 创建实体类

src/main/java/hello/User.java

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

3.6 创建仓库类repository

src/main/java/hello/UserRepository.java

package hello;

import org.springframework.data.repository.CrudRepository;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Long> {

}

这里的仓库类只是个接口,Spring会帮我们实现,并且注册的bean的名字就是userRepository

3.7 创建控制器controller

src/main/java/hello/MainController.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
    @Autowired // This means to get the bean called userRepository
               // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}

上面的例子同样没有指定HTTP的方法,GET,POST或者PUT等,因为@GetMapping等同于@RequestMapping(method=GET)

3.7 创建启动类

src/main/java/hello/Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4 测试

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐