javascript
H2数据库的Spring Boot
在本快速教程中,我們將引導一個由內存H2數據庫支持的簡單Spring Boot應用程序。 我們將使用Spring Data JPA與我們的數據庫進行交互。
項目設置:
首先,讓我們使用Spring Initializr生成我們的項目模板:
單擊“生成項目”鏈接后,將下載我們的項目文件。
現在,如果我們仔細查看生成的POM文件,將在下面添加依賴項:
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-test</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > < dependency > < groupId >com.h2database</ groupId > < artifactId >h2</ artifactId > < scope >runtime</ scope > </ dependency >H2默認屬性:
由于我們已經添加了H2數據庫依賴關系,因此Spring Boot將自動配置其相關屬性。 默認配置包括:
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled= false讓我們通過在application.properties文件中定義這些屬性來覆蓋其中一些屬性:
spring.h2.console.enabled= true spring.h2.console.path= /h2 spring.datasource.url=jdbc:h2:mem:university在這里,我們的數據庫名稱將是一所大學 。 我們還啟用了H2控制臺并設置了其上下文路徑。
定義實體:
現在,我們將定義一個Student實體:
@Entity public class Student { @Id @GeneratedValue (strategy = GenerationType.AUTO) private Integer id; ?private String name; ????public Student(String name) { this .name = name; } ?//getters, setters ?public String toString() { return "{id=" + id + ", name=" + name + "}" ; } }及其對應的Spring Data JPA存儲庫:
@Repository public interface StudentRepository extends CrudRepository<Student, Integer> { }學生實體將以完全相同的名稱映射到數據庫表。 如果需要,可以使用@Table批注指定其他表名。
應用類別:
最后,讓我們實現我們的UniversityApplication類:
@SpringBootApplication public class UniversityApplication { ?public static void main(String[] args) { SpringApplication.run(UniversityApplication. class , args); } ?@Bean public CommandLineRunner testApp(StudentRepository repo) { return args -> { repo.save( new Student( "James" )); repo.save( new Student( "Selena" )); ?List<Student> allStudents = repo.findAll(); System.out.println( "All students in DB: " + allStudents); ?Student james = repo.findById( 1 ); System.out.println( "James: " + james); }; } }此類是我們Spring Boot應用程序的起點。 在這里, @SpringBootApplication注釋等效于將@ ComponentScan,@ EnableAutoConfiguration和@SpringConfiguration組合在一起。
我們還定義了CommandLineRunner的實例。 因此,當我們運行應用程序時,控制臺日志將具有:
UniversityApplication:All students in DB: [{id= 1 , name=James} , {id= 2 , name=Selena}] James: {id= 1 , name=James} ...請注意,在Spring Boot中, 理想情況下 , 所有實體都應在與主應用程序類相同的包級別或更低的級別(在子包中)定義 。 如果是這樣,Spring Boot將自動掃描所有這些實體。
訪問H2控制臺:
我們還可以在H2控制臺上檢查數據庫條目。
為此,我們將在任何瀏覽器上打開URL: http:// localhost:8080 / h2并使用我們的數據庫配置登錄。 有了它,我們將能夠在UI Console儀表板上輕松查看所有創建的表和條目。
結論:
在本教程中,我們使用單個實體引導了一個非常簡單的Spring Boot應用程序。 該應用程序與H2數據庫集成在一起,并使用Spring Data JPA。
我們可以輕松擴展它,以適應更廣泛的應用范圍。
翻譯自: https://www.javacodegeeks.com/2019/09/spring-boot-with-h2-database.html
總結
以上是生活随笔為你收集整理的H2数据库的Spring Boot的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 情侣头像真人有电脑系统(qq头像真人情侣
- 下一篇: Spring Framework中的作用