Demo project for Spring Boot 【1】spring-boot-starter【2】spring-boot-starter-data-jpa

在Spring Boot中,你可以使用spring-boot-starterspring-boot-starter-data-jpa这两个starter来快速创建一个基于Spring Boot和JPA的演示项目。下面是一个简单的步骤说明:

  1. 创建新项目
    如果你使用的是Maven,你可以在命令行中运行以下命令来创建一个新的Spring Boot项目:
mvn archetype:generate -DgroupId=com.example -DartifactId=demo-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

如果你使用的是Gradle,你可以运行以下命令:

gradle init --type basic-application
  1. 添加依赖
    在你的pom.xml文件中,添加以下依赖:
    Maven:
<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- Spring Boot Starter Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2 Database (for development only) -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- JPA Hibernate Integration (needed by spring-boot-starter-data-jpa) -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    </dependency>
</dependencies>

Gradle:

dependencies {
    // Spring Boot Starter
    implementation 'org.springframework.boot:spring-boot-starter'
    // Spring Boot Starter Data JPA
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // H2 Database (for development only)
    runtimeOnly 'com.h2database:h2'
    // JPA Hibernate Integration (needed by spring-boot-starter-data-jpa)
    implementation 'org.hibernate:hibernate-core'
}
  1. 配置数据库连接
    src/main/resources目录下,创建一个名为application.properties的文件,并添加以下内容:
    Maven:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true # 开启H2控制台,方便调试时查看数据库内容。生产环境建议关闭。

Gradle:
如果你使用的是.gradle文件,你可以在src/main/resources目录下创建一个名为application.properties的文件,并添加以下内容:
4. 创建实体类
src/main/java/com/example/demo/domain目录下,创建一个名为User的Java类,并添加以下内容:
Maven:

package com.example.demo.domain; // 确保这个包名与你的pom.xml文件中的<packaging>java</packaging>相匹配。如果不匹配,你需要更改这个包名以使其与<packaging>标签匹配。
import javax.persistence.*; // 引入JPA相关的注解。你也可以选择引入其他JPA库提供的注解。这取决于你的项目需求。在这里,我们使用Spring Boot Starter Data JPA所提供的注解。如果你使用其他的JPA库,你可能需要引入相应的注解库。例如,如果你使用Hibernate,你可能需要引入hibernate-core库。如果你使用其他的JPA实现,你可能需要引入相应的JPA实现库。例如,如果你使用EclipseLink,你可能需要引入eclipselink库。在使用这些库之前,请确保你已经了解了它们的文档和用法。这里我们假设你使用的是Spring Boot Starter Data JPA所提供的注解库。
Accessing data with MySQL
This guide walks you through the process of creating a Spring application connected to a MySQL Database (as opposed to an in-memory, embedded database, which most of the other guides and many sample applications use). It uses Spring Data JPA to access the database, but this is only one of many possible choices (for example, you could use plain Spring JDBC).MySQL访问数据
本指南将引导您完成创建一个连接到MySQL数据库的Spring应用程序的过程(与其他大多数指南和许多示例应用程序使用的内存中的嵌入式数据库不同)。它使用springdatajpa来访问数据库,但这只是许多可能的选择之一(例如,您可以使用普通springjdbc)。

Here, spring.jpa.hibernate.ddl-auto can be none, update, create, or create-drop. See the Hibernate documentation for details.
    none: The default for MySQL. No change is made to the database structure.
    update: Hibernate changes the database according to the given entity structures.
    create: Creates the database every time but does not drop it on close.
    create-drop: Creates the database and drops it when SessionFactory closes.
You must begin with either create or update, because you do not yet have the database structure. After the first run, you can switch it to update or none, according to program requirements. Use update when you want to make some change to the database structure.
The default for H2 and other embedded databases is create-drop. For other databases, such as MySQL, the default is none.

在这里,spring.jpa.hibernate.ddl auto可以是none、update、create或create drop。有关详细信息,请参阅Hibernate文档。
无:MySQL的默认值。不会对数据库结构进行任何更改。
更新:Hibernate根据给定的实体结构更改数据库。
create:每次创建数据库,但在关闭时不删除它。
createdrop:创建数据库并在SessionFactory关闭时删除它。
必须从create或update开始,因为您还没有数据库结构。第一次运行后,您可以根据程序要求将其切换为update或none。如果要对数据库结构进行某些更改,请使用update。
H2和其他嵌入式数据库的默认值是createdrop。对于其他数据库,例如MySQL,默认值为none。

For this example, you need not modify the AccessingDataMysqlApplication class.
@SpringBootApplication is a convenience annotation that adds all of the following:
    @Configuration: Tags the class as a source of bean definitions for the application context.
    @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
    @ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.

对于本例,不需要修改AccessingDataMysqlApplication类。
@SpringBootApplication是一个方便的注释,它添加了以下所有内容:
@配置:将类标记为应用程序上下文的bean定义源。
@EnableAutoConfiguration:告诉springboot根据类路径设置、其他bean和各种属性设置开始添加bean。例如,如果springwebmvc在类路径上,这个注释将应用程序标记为web应用程序并激活关键行为,例如设置一个DispatcherServlet@ComponentScan:告诉Spring在com/example包中查找其他组件、配置和服务,让它找到控制器。
main()方法使用springboot的SpringApplication.run()启动应用程序的方法。你注意到没有一行XML?没有web.xml文件文件,或者。这个web应用程序是100%Java的,您不需要配置任何管道或基础设施。

Build an executable JAR
You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

构建一个可执行的JAR
您可以使用GradleMaven从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的可执行JAR文件并运行它。在整个开发过程中,作为一个可执行的应用程序,可以很容易地在整个开发过程中部署一个不同的jar版本。

Make Some Security Changes
When you are on a production environment, you may be exposed to SQL injection attacks. A hacker may inject DROP TABLE or any other destructive SQL commands. So, as a security practice, you should make some changes to your database before you expose the application to your users.
The following command revokes all the privileges from the user associated with the Spring application:
mysql> revoke all on db_example.* from 'springuser'@'%';
Now the Spring application cannot do anything in the database.
The application must have some privileges, so use the following command to grant the minimum privileges the application needs:
mysql> grant select, insert, delete, update on db_example.* to 'springuser'@'%';
Removing all privileges and granting some privileges gives your Spring application the privileges necessary to make changes to only the data of the database and not the structure (schema).
When you want to make changes to the database:
    Regrant permissions.
    Change the spring.jpa.hibernate.ddl-auto to update.
    Re-run your applications.
Then repeat the two commands shown here to make your application safe for production use again. Better still, use a dedicated migration tool, such as Flyway or Liquibase.

进行一些安全更改
当您在生产环境中时,您可能会受到SQL注入攻击。黑客可以注入DROP TABLE或任何其他破坏性的SQL命令。因此,作为安全实践,您应该在向用户公开应用程序之前对数据库进行一些更改。
以下命令将撤消与Spring应用程序关联的用户的所有特权:
mysql>revoke all on db_example.*from'springuser'@%';
现在Spring应用程序不能在数据库中做任何事情。
应用程序必须具有某些权限,因此请使用以下命令授予应用程序所需的最低权限:
mysql>grant select,insert,delete,update on db\u example.*到'springuser'@%';
删除所有特权并授予某些特权将使您的Spring应用程序获得只更改数据库数据而不更改结构(模式)所需的权限。
要更改数据库时:
重新分配权限。
改变spring.jpa.hibernate.ddl自动更新。
重新运行应用程序。
然后重复这里显示的两个命令,使您的应用程序再次安全地用于生产。更好的是,使用专用的迁移工具,比如FlywayLiquibase![在这里插入图片描述](https://img-blog.csdnimg.cn/20200807132736941.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Jsb2dfcHJvZ3JhbWI=,size_16,color_FFFFFF,t_70)

```java
package com.example.accessingdatamysql;

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

@SpringBootApplication
public class AccessingDataMysqlApplication {

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

}
package com.example.accessingdatamysql;

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;
  }
}
package com.example.accessingdatamysql;

import org.springframework.data.repository.CrudRepository;

import com.example.accessingdatamysql.User;

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

public interface UserRepository extends CrudRepository<User, Integer> {

}
package com.example.accessingdatamysql;

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.PostMapping;
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;

  @PostMapping(path="/add") // Map ONLY POST 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();
  }
}
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo-mysql</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo-mysql</name>
	<description>Demo project for Spring Boot</description>

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

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

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

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

</project>


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

2020-08-07 13:19:10.330  INFO 17380 --- [           main] c.e.a.AccessingDataMysqlApplication      : Starting AccessingDataMysqlApplication on PC-202008012041 with PID 17380 (G:\eclipse-workspace-Jee\demo-mysql\target\classes started by Administrator in G:\eclipse-workspace-Jee\demo-mysql)
2020-08-07 13:19:10.332  INFO 17380 --- [           main] c.e.a.AccessingDataMysqlApplication      : No active profile set, falling back to default profiles: default
2020-08-07 13:19:10.880  INFO 17380 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-08-07 13:19:10.996  INFO 17380 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 108ms. Found 1 JPA repository interfaces.
2020-08-07 13:19:11.418  INFO 17380 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-08-07 13:19:11.428  INFO 17380 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-07 13:19:11.429  INFO 17380 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-07 13:19:11.431  INFO 17380 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.24] using APR version [1.7.0].
2020-08-07 13:19:11.431  INFO 17380 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2020-08-07 13:19:11.431  INFO 17380 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2020-08-07 13:19:11.437  INFO 17380 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1g  21 Apr 2020]
2020-08-07 13:19:11.559  INFO 17380 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-07 13:19:11.560  INFO 17380 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1183 ms
2020-08-07 13:19:11.720  INFO 17380 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-07 13:19:11.752  INFO 17380 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-08-07 13:19:11.780  WARN 17380 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-08-07 13:19:11.795  INFO 17380 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-08-07 13:19:11.915  INFO 17380 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-08-07 13:19:12.007  INFO 17380 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-08-07 13:19:12.181  INFO 17380 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-07 13:19:12.183  INFO 17380 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-08-07 13:19:14.752  INFO 17380 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-08-07 13:19:14.776  INFO 17380 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-08-07 13:19:16.664  INFO 17380 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-08-07 13:19:16.673  INFO 17380 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-07 13:19:17.260  INFO 17380 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-08-07 13:19:17.267  INFO 17380 --- [           main] c.e.a.AccessingDataMysqlApplication      : Started AccessingDataMysqlApplication in 7.234 seconds (JVM running for 9.419)
2020-08-07 13:22:03.582  INFO 17380 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-07 13:22:03.583  INFO 17380 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-07 13:22:03.592  INFO 17380 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值