Spring Boot お勉強 その2 ~インメモリDBアクセス~

今回はSpring BootでのDBアクセスについて書きます。
DBはH2データベースを使用します。
まずはGradleの設定から。

<略>
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}
<略>

中の2行を追記しました。
これでビルドすると、クラスパスにspring-data-jpa関連のライブラリとH2のjarファイルが追加されます。
spring-bootはクラスパス内のH2のドライバやなんかを読み込んで、それに合ったDB接続の設定を自動的にやってくれるというわけです。


確認のために次のようなクラス・インターフェースを作ります。

@Entity
public class TestEntity {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	public Integer getId() {
		return id;
	}
}
@Repository
public interface TestRepository extends JpaRepository<TestEntity, Integer> {
	
}

これらが使用している技術はJPAだったりSpring-Hibernate連携だったりで、Bootと直接は関係ないので詳細は割愛します。


次にテストクラスを書いて、src/test/java配下のどこかに置きます。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class TestRepositoryTests {
	
	@Autowired
	private TestRepository repo;
	
	@Test
	public void testName() throws Exception {
		TestEntity e = new TestEntity();
		repo.save(e);
		
		List<TestEntity> savedEList = repo.findAll();
		Assert.assertEquals(savedEList.size(), 1);
	}
}

この状態でGradleからビルドを実行すると、テストコードが実行されます。
その中で、Repositoryインターフェースを通してEntityがDBに保存され、取り出されます。
これでDBへのinsert、selectが実行できたわけですが、正直DBにアクセスできた実感がないですね。
だってDBがオンメモリで動いて実行後に消えてしまうわけですから。
DBをファイルに書き出して、確認するのはまた次回。
では。