如何将硬编码数据添加到Spring Boot项目中,以便在运行后存入数据库。

huangapple go评论81阅读模式
英文:

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&#39;m fairly new to Spring, so there&#39;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&#39;ve decided to implement a PostgreSQL database. 

I&#39;ve worked on a few Spring projects in the past, and if I&#39;m remembering correctly, you can hardcode some instances of the models that you&#39;ve created for testing purposes. So, when you run the Spring boot application, these instances will already be in the database, so I wouldn&#39;t have to add it through pgAdmin or the sql shell myself after the fact. 

I&#39;m confused as to where exactly I would &quot;hard-code&quot; 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&#39;s where my spring boot program is being run, but I&#39;m unsure.

Here&#39;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 = &quot;genericName&quot;)
private String genericName;
@Column(name = &quot;brandNames&quot;)
private ArrayList&lt;String&gt; brandNames;
@Column(name = &quot;strength&quot; )
private String strength;
@Column(name = &quot;quantity&quot;)
private int quantity; 
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = &quot;pharm_commonuses&quot;,
joinColumns = { @JoinColumn(name = &quot;pharmaceutical_id&quot;) },
inverseJoinColumns = { @JoinColumn(name = &quot;commonUse_id&quot;) })
private Set&lt;CommonUse&gt; commonUses = new HashSet&lt;&gt;();
public Pharmaceutical() {}
public Pharmaceutical(String genericName, ArrayList&lt;String&gt; 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&lt;String&gt; getBrandNames() {
return brandNames;
}
public void setBrandNames(ArrayList&lt;String&gt; 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 &quot;Pharmaceutical [id=&quot; + id + &quot;, genericName=&quot; + genericName + &quot;, brandNames=&quot; + brandNames
+ &quot;, strength=&quot; + strength + &quot;, quantity=&quot; + quantity + &quot;, commonUses=&quot; + commonUses + &quot;]&quot;;
}
public Set&lt;CommonUse&gt; 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**
```
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;parent&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
&lt;version&gt;2.3.2.RELEASE&lt;/version&gt;
&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
&lt;/parent&gt;
&lt;groupId&gt;com.oasis&lt;/groupId&gt;
&lt;artifactId&gt;inventory&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;inventory&lt;/name&gt;
&lt;description&gt;pharmaceuticals inventory management system&lt;/description&gt;
&lt;properties&gt;
&lt;java.version&gt;11&lt;/java.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;optional&gt;true&lt;/optional&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.postgresql&lt;/groupId&gt;
&lt;artifactId&gt;postgresql&lt;/artifactId&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
&lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;
```
</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&#39;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>

huangapple
  • 本文由 发表于 2020年8月19日 02:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63474287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定