環(huán)境:spring boot+jpa+postgresql(總結(jié)參考了其他博文)
1痕钢、首先設(shè)置連接數(shù)據(jù)庫pom的依賴:
<!-- 數(shù)據(jù)庫-->?
? ? ? ? ? <dependency>?
? ? ? ? ? ? ? ? ? ?<groupId>org.springframework.boot</groupId>?
? ? ? ? ? ? ? ? ? ? <artifactId>spring-boot-starter-jdbc</artifactId>?
? ? ? ? </dependency>
? ? ? ?<dependency>
? ? ? ? ? ? ? ? ? ? ?<groupId>org.postgresql</groupId>
? ? ? ? ? ? ? ? ? ? ? <artifactId>postgresql</artifactId>?
? ? ? ? ? ? ? ? ? ? ? <scope>runtime</scope>
? ? ? ? ?</dependency>?
? ? ? ? ?<dependency>
? ? ? ? ? ? ? ? ? ? <groupId>org.springframework.boot</groupId>?
? ? ? ? ? ? ? ? ? ?<artifactId>spring-boot-starter-data-jpa</artifactId>
? ? ? ? ?</dependency>
2脖隶、application.properties中pgsql數(shù)據(jù)庫連接的配置(可自行改為yml文件形式):
spring.datasource.url=jdbc:postgresql://localhost:5432/table_name
spring.datasource.username=postgres? ? ? ? ? ?
spring.datasource.password=********
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
#在控制臺打印運(yùn)行的sql語句:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
#防止啟動時打印出“java.sql.SQLFeatureNotSupportedException: 這個 org.postgresql.jdbc.PgConnection.createClob() 方法尚未被實作梧躺±缺椋”的異常:
properties.hibernate.temp.use_jdbc_metadata_defaults=false
3、基本在以上步驟就可以連接postgerSQL了骚勘,我使用jpa進(jìn)行內(nèi)部的數(shù)據(jù)庫設(shè)置:
###創(chuàng)建實體表時虹茶,user 在 postgresql 中為保留關(guān)鍵字刀森,所以如果你persist一個名為User的類的時候就會報語法錯誤踱启。在這個地方搞了好久,偶然在一個博客上看到的,有相同問題的可以測試一下:
數(shù)據(jù)庫實體表
持久層(jpa已經(jīng)集成了基本的增刪改查埠偿,也可如圖來擴(kuò)展):
持久層
控制層:
控制層