JPAのボイラープレートを無くしてくれるSpring Data JPA、これないとJPA開発がきついのですが、実はこのライブラリはCDIのExtension
も用意されています。
使い方は簡単。以下の依存関係を定義して、
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
EntityManager
を@Produces
でproduceして、
@Dependent
public class EntityManagerFactoryProducer {
@PersistenceContext(name = "myPU")
EntityManager entityManager;
@Produces
@RequestScoped
public EntityManager createEntityManager() {
return entityManager;
}
}
Repository
インタフェースを作るだけ。
@Dependent
public interface PointRepository extends JpaRepository<Point, Integer> {
}
あとはCDIのBeanにインジェクションするだけです。
@ApplicationScoped
@Transactional
public class PointService {
@Inject
PointRepository pointRepository;
public List<Point> findAll() {
return pointRepository.findAll();
}
public Point create(Point point) {
return pointRepository.save(point);
}
}
Repository
クラスにCDIのアノテーションをつけない場合は、beans.xml
を作って
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
を設定する必要があります。
Repository
クラスの作り方はマニュアルを見てください。
この辺も参考になります。
サンプルコードはこちら。 このサンプルではMVC 1.0を使っているのですが、ここまで来るとほとんどSpringですね。
拙著「はじめてのSpring Boot」の内容も結構使えると思います。