Spring Data JPA

利用操作物件的方式,對資料庫做新增、修改、刪除、更新的動作,不用撰寫一堆雜亂的 SQL 語法,只要連線資訊對了,更換資料庫也不用擔心程式需要另外調整。

邦哥不會寫程式
Nov 1 · 3 min read

使用工具

intelliJ IDEA CE
SQL Server 2017
Java 8

SQL Server JDBC Gradle dependency

首先,在 build.gradle 加入下列設定,SQL Server 版本所用的版本號會有所區別

implementation group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.4.1.jre8'

Database 建立 Table

如果資料庫中尚未有 Table 的話,先建立要操作的 Table,下列指令以 UserInfo 為例

CREATE TABLE USER_INFO (ID INT, NAME NVARCHAR(50), AGE INT)
GO

建立 Table Model

建立 DAO

建立 Controller

發送 Request

接著可以測試一下寫好的程式囉~

可以看到資料表中成功加入一筆 user 了

執行出錯啦

Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set

在 application.properties 中新增下列設定即可

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect

SHOW SQL

如果想查看操作過程的 SQL 指令,可以在 application.properties 中新增下列設定

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

參考來源

程式裡有蟲

工程師的日常,用程式解決生活大小事

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade