IK.AM

@making's tech note


Spring Data JPAをCDIから使う

🗃 {Programming/Java/org/springframework/data/jpa}
🏷 CDI 🏷 Java 🏷 Java EE 7 🏷 MVC 🏷 Spring Data JPA 
🗓 Updated at 2015-04-22T15:33:56Z  🗓 Created at 2015-04-22T15:33:56Z   🌎 English Page

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」の内容も結構使えると思います。


✒️️ Edit  ⏰ History  🗑 Delete