S-JIS[2017-09-15/2017-10-22] 変更履歴

Spring Boot JPA

Spring BootでJPAを扱う方法について。


概要

JPA(Java Persistence API)は、データを永続化(保存)する為のAPI。
大抵は、永続化とはRDBに保存することを指す。

Spring BootでJPAを扱うにはJPAとJDBCのライブラリーを使用する。
また、RDBのライブラリーも指定する。

build.gradle:

〜
dependencies {
	compile('org.springframework.boot:spring-boot-starter-data-rest') // REST
	compile('org.springframework.boot:spring-boot-starter-security') // 認証
	compile('org.springframework.boot:spring-boot-starter-thymeleaf')
	compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4')

	compile("org.springframework.boot:spring-boot-starter-data-jpa")
//	compile("org.springframework.boot:spring-boot-starter-jdbc") // 不要かも?
	compile("com.h2database:h2") // H2DB

	runtime('org.springframework.boot:spring-boot-devtools')

	testCompile('org.springframework.boot:spring-boot-starter-test')
	testCompile('org.springframework.security:spring-security-test')
}

SQLログ出力

JPAで発行されるSQLをログ出力しておくようにすると、デバッグ時に便利。

SQL文のログ(PreparedStatementのSQL文)を出力するには以下のように指定する。
(プログラム上はdebugレベルで出力するようになっているので、それをコンソールに出力するようにする指定)

src/main/resources/application.properties:

logging.level.org.hibernate.SQL=debug

バインドする値を表示するには以下のような設定も加える。

#logging.level.org.hibernate.type.descriptor.sql=trace
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=trace
logging.level.org.hibernate.type.EnumType=trace

Spring Bootへ戻る / Spring Frameworkへ戻る / 技術メモへ戻る
メールの送信先:ひしだま