英文:
How to add Hard-coded Data to Spring Boot Project so it's in Database after Running
问题
以下是你提供的文本的中文翻译部分:
抱歉关于问题标题的问题。我对如何表达问题并不确定。
一些背景:我对Spring相当新,所以有很多与Spring相关的东西都完全超出了我的理解范围。我最近开始了一个新的实践项目,创建了一个药品库存应用程序。截至目前,我已经设置了我的模型和存储库。我决定实现一个PostgreSQL数据库。
我过去曾经做过一些Spring项目,如果我记得正确的话,你可以为了测试目的硬编码一些你已经创建的模型实例。因此,当你运行Spring引导应用程序时,这些实例将已经存在于数据库中,因此我不需要在事后通过pgAdmin或sql shell自己添加它。
我困惑的是我应该在什么地方“硬编码”这些信息,以及它是否应该是JSON格式。我认为它应该放在我的InventoryApplication.java的主要函数中,因为那是我Spring引导程序运行的地方,但我不确定。
以下是我项目中的一些文件,以便了解项目的流程:
InventoryApplication.java
package com.oasis.inventory;
import com.oasis.inventory.model.*;
import com.oasis.inventory.repository.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
Pharmaceutical.java
package com.oasis.inventory.model;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "pharmaceuticals")
public class Pharmaceutical {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "genericName")
private String genericName;
@Column(name = "brandNames")
private ArrayList<String> brandNames;
@Column(name = "strength" )
private String strength;
@Column(name = "quantity")
private int quantity;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "pharm_commonuses",
joinColumns = { @JoinColumn(name = "pharmaceutical_id") },
inverseJoinColumns = { @JoinColumn(name = "commonUse_id") })
private Set<CommonUse> commonUses = new HashSet<>();
public Pharmaceutical() {}
public Pharmaceutical(String genericName, ArrayList<String> brandNames, String strength,
int quantity) {
this.genericName = genericName;
this.brandNames = brandNames;
this.strength = strength;
this.quantity = quantity;
}
public String getGenericName() {
return genericName;
}
public void setGenericName(String genericName) {
this.genericName = genericName;
}
public ArrayList<String> getBrandNames() {
return brandNames;
}
public void setBrandNames(ArrayList<String> brandNames) {
this.brandNames = brandNames;
}
public String getStrength() {
return strength;
}
public void setStrength(String strength) {
this.strength = strength;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public long getId() {
return id;
}
@Override
public String toString() {
return "Pharmaceutical [id=" + id + ", genericName=" + genericName + ", brandNames=" + brandNames
+ ", strength=" + strength + ", quantity=" + quantity + ", commonUses=" + commonUses + "]";
}
public Set<CommonUse> getCommonUses() {
return commonUses;
}
}
application.properties
server.port=8081
spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=postgres
spring.datasource.password= sEcReT
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
# For prod, change to validate
spring.jpa.hibernate.ddl-auto= update
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 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.oasis</groupId>
<artifactId>inventory</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>inventory</name>
<description>pharmaceuticals inventory management system</description>
<properties>
<java.version>11</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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>
<details>
<summary>英文:</summary>
I apologize about the title of the question. I was exactly sure how to word the question.
A little background: I'm fairly new to Spring, so there's fairly a lot of things Spring-related that go completely over my head. I recently started a new practice project where I create an inventory application for medicines. As of now, I have my models and repositories set up. I've decided to implement a PostgreSQL database.
I've worked on a few Spring projects in the past, and if I'm remembering correctly, you can hardcode some instances of the models that you've created for testing purposes. So, when you run the Spring boot application, these instances will already be in the database, so I wouldn't have to add it through pgAdmin or the sql shell myself after the fact.
I'm confused as to where exactly I would "hard-code" this information and whether or not it would be in JSON format. I think it would go in the main function of my InventoryApplication.java because that's where my spring boot program is being run, but I'm unsure.
Here's a few of my files in order to understand the flow of my project:
**InventoryApplication.java**
package com.oasis.inventory;
import com.oasis.inventory.model.;
import com.oasis.inventory.repository.;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
**pharmaceutical.java**
package com.oasis.inventory.model;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "pharmaceuticals")
public class Pharmaceutical {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "genericName")
private String genericName;
@Column(name = "brandNames")
private ArrayList<String> brandNames;
@Column(name = "strength" )
private String strength;
@Column(name = "quantity")
private int quantity;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "pharm_commonuses",
joinColumns = { @JoinColumn(name = "pharmaceutical_id") },
inverseJoinColumns = { @JoinColumn(name = "commonUse_id") })
private Set<CommonUse> commonUses = new HashSet<>();
public Pharmaceutical() {}
public Pharmaceutical(String genericName, ArrayList<String> brandNames, String strength,
int quantity) {
this.genericName = genericName;
this.brandNames = brandNames;
this.strength = strength;
this.quantity = quantity;
}
public String getGenericName() {
return genericName;
}
public void setGenericName(String genericName) {
this.genericName = genericName;
}
public ArrayList<String> getBrandNames() {
return brandNames;
}
public void setBrandNames(ArrayList<String> brandNames) {
this.brandNames = brandNames;
}
public String getStrength() {
return strength;
}
public void setStrength(String strength) {
this.strength = strength;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public long getId() {
return id;
}
@Override
public String toString() {
return "Pharmaceutical [id=" + id + ", genericName=" + genericName + ", brandNames=" + brandNames
+ ", strength=" + strength + ", quantity=" + quantity + ", commonUses=" + commonUses + "]";
}
public Set<CommonUse> getCommonUses() {
return commonUses;
}
}
**application.properties**
server.port=8081
spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=postgres
spring.datasource.password= sEcReT
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
Hibernate ddl auto (create, create-drop, validate, update)
For prod, change to validate
spring.jpa.hibernate.ddl-auto= update
**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 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.oasis</groupId>
<artifactId>inventory</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>inventory</name>
<description>pharmaceuticals inventory management system</description>
<properties>
<java.version>11</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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>
```
</details>
# 答案1
**得分**: 1
这距离一个问题已经接近两年了,我相信你已经想出了解决方案。我仍然想分享一下,万一有人正在寻找相同的解决方案。
你可以使用`CommandLineRunner`来执行事务,比如将记录持久化到数据库中。然而,每次应用程序启动时都会执行这个操作,这可能会导致不需要的副作用,但你可以在本地开发中尝试一下。
正如@martinspielmann建议的,你可以使用[FlywayDB](https://flywaydb.org/documentation/usage/plugins/springboot)或者[Liquibase](https://docs.liquibase.com/tools-integrations/springboot/using-springboot-with-maven.html)来完成这个任务。你可以创建带有版本的SQL文件,这些文件可以包含多个查询,用于不同的事务(CRUD),包括创建/修改表等数据库操作。
<details>
<summary>英文:</summary>
It's close to a 2 year old question and I believe you have come up with a solution. I still wanted to share just in case someone would be looking for the same.
You can use `CommandLineRunner` to execute a transaction like persisting a record into the database. However, every time your application starts up it will always execute this and will lead to unwanted side effects but you can try it in your local development.
As @martinspielmann recommended, you can use [FlywayDB](https://flywaydb.org/documentation/usage/plugins/springboot) or [Liquibase](https://docs.liquibase.com/tools-integrations/springboot/using-springboot-with-maven.html) to do the job. You can create versioned SQL files that may contain several queries for different transactions (CRUD) including database operations like creating/alter tables and more.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论