Doma 2とは?基本的な使い方は?
下記の記事を参考にしてください。2014年のJavaアドベントカレンダー向けに書いたものです。
美しき青きDoma!~SQLとIDEが奏でる美しきORマッピング~ - Java EE 事始め!
Domaでは、プログラマが作るのはHogeDaoインターフェイスだけで、その実装クラスはビルド時にAnnotation Processorで自動生成されます。
で、CDI使ってインジェクションしたり、JTAでトランザクション管理するには、実装クラスに@RequestScoped
などのアノテーションを付加する必要があります。
その方法がずっと分からなかったのですが、遂にやり方が分かったのでご紹介します。
ソースはGitHubに公開しています。
MasatoshiTada/doma-jaxrs · GitHub
APサーバーはPayara Web 4.1.153です。DBはPayara内包のJavaDBを使っています。IDEはIntelliJです。
CDI管理にする答えは@AnnnotateWith
ツイッターである方々のやり取りを見ていたら、Doma 2の公式ドキュメントの一部が目に入りました。
http://doma.readthedocs.org/ja/stable/config/#id22
@AnnnotateWith
というアノテーションを使っていますね。これがポイントです。
ということで、こんなアノテーションを自作します。
package com.example.dao.config; import org.seasar.doma.AnnotateWith; import org.seasar.doma.Annotation; import org.seasar.doma.AnnotationTarget; import javax.enterprise.context.Dependent; import javax.inject.Inject; @AnnotateWith(annotations = { @Annotation(target = AnnotationTarget.CLASS, type = Dependent.class) , @Annotation(target = AnnotationTarget.CONSTRUCTOR, type = Inject.class) }) public @interface InjectConfig { }
このアノテーションを、自作Daoインターフェイスに付加します。
package com.example.dao; import com.example.dao.config.InjectConfig; import com.example.entity.Employee; import org.seasar.doma.Dao; import org.seasar.doma.Script; import org.seasar.doma.Select; import java.util.List; import java.util.Optional; @Dao @InjectConfig public interface EmployeeDao { @Script void create(); @Select Optional<Employee> selectById(Integer empId); @Select List<Employee> selectLikeName(String name); }
で、GradleでビルドするとDaoインターフェイス実装クラスが作成されます。
package com.example.dao; /** */ @javax.enterprise.context.Dependent() @javax.annotation.Generated(value = { "Doma", "2.5.0" }, date = "2015-10-15T20:48:55.929+0900") public class EmployeeDaoImpl extends org.seasar.doma.internal.jdbc.dao.AbstractDao implements com.example.dao.EmployeeDao { /** * @param config the config */ @javax.inject.Inject() public EmployeeDaoImpl(org.seasar.doma.jdbc.Config config) { super(config); }
@AnnnotateWith
で指定した通り、クラスに@Dependent
、コンストラクタに@Inject
が付加されています。これで、DaoImplを他のクラスにCDIでインジェクトできるようになります。
そして、コンストラクタインジェクションされるConfig実装クラスはコレです。
package com.example.dao.config; import com.example.dao.datasource.DataSourceProducer; import com.example.dao.qualifier.DerbyQualifier; import com.example.exception.dto.ExceptionDto; import org.seasar.doma.jdbc.Config; import org.seasar.doma.jdbc.dialect.Dialect; import org.seasar.doma.jdbc.dialect.MysqlDialect; import javax.annotation.Resource; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import javax.sql.DataSource; @ApplicationScoped public class AppConfig implements Config { @Inject @DerbyQualifier private DataSourceProducer dataSourceProducer; @Override public DataSource getDataSource() { return dataSourceProducer.getDataSource(); } @Override public Dialect getDialect() { return dataSourceProducer.getDialect(); } }
@ApplicationScoped
を付加してCDI管理ビーンにします。で、Config実装クラスはこの1つしかないので、先ほどのEmployeeDaoImplにコンストラクタインジェクションされる、という訳です。
データソースが複数ある場合など、Config実装クラスが複数になる可能性があると思います。その場合はQualifierを自作して、それをConfig実装クラスと@AnnotatedWith
に追加すれば良いはずです。
(CDIやQualifierについては、最後に紹介している寺田さんの資料をご確認ください)
@AnnotateWith(annotations = { @Annotation(target = AnnotationTarget.CLASS, type = Dependent.class) , @Annotation(target = AnnotationTarget.CONSTRUCTOR, type = Inject.class) , @Annotation(target = AnnotationTarget.CONSTRUCTOR_PARAMETER, type = 自作Qualifier1.class }) public @interface InjectConfig1 { }
@ApplicationScoped @自作Qualifier1 public class AppConfig1 implements Config { // 省略 }
@AnnotateWith(annotations = { @Annotation(target = AnnotationTarget.CLASS, type = Dependent.class) , @Annotation(target = AnnotationTarget.CONSTRUCTOR, type = Inject.class) , @Annotation(target = AnnotationTarget.CONSTRUCTOR_PARAMETER, type = 自作Qualifier2.class }) public @interface InjectConfig2 { }
@ApplicationScoped @自作Qualifier2 public class AppConfig2 implements Config { // 省略 }
JTAでトランザクション管理する
DataSource
は@Resource
で取ってきているし、DaoImplクラスはCDI管理にできたので、後は簡単です。
package com.example.service; import com.example.dao.EmployeeDao; import com.example.entity.Employee; import com.example.resource.dto.EmployeeDto; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.transaction.Transactional; import java.io.Serializable; import java.util.Optional; @Dependent public class EmployeeService implements Serializable { @Inject private EmployeeDao employeeDao; @Transactional(Transactional.TxType.REQUIRED) public Optional<EmployeeDto> selectById(Integer empId) { Optional<Employee> employeeOptional = employeeDao.selectById(empId); return employeeOptional.map(this::convertToDto); }
@Inject
でインジェクトすると、EmployeeDaoImpl
のインスタンスが注入されます。で、メソッドに@Transactional
を付加すればOK!
JAX-RSでRESTを作る
package com.example.resource; import com.example.resource.dto.EmployeeDto; import com.example.service.EmployeeService; import org.hibernate.validator.constraints.NotBlank; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.validation.constraints.Pattern; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("employees") @RequestScoped public class EmployeeResource { @Inject private EmployeeService employeeService; @GET @Path("{empId}") @Produces(MediaType.APPLICATION_JSON) public Response selectById(@PathParam("empId") @Pattern(regexp = "[1-9][0-9]*") String empIdStr) { Integer empId = Integer.valueOf(empIdStr); EmployeeDto employeeDto = employeeService.selectById(empId) .orElseThrow(() -> new NotFoundException("該当する社員が見つかりませんでした")); return Response.ok(employeeDto).build(); } }
感想
これで去年からの疑問点が解決しました。ようやっとスッキリです。
あとはDomaの使い方さえ知れれば、怖いものなし・・・のはず!
併せて読みたい
JTAの解説ブログ。いつもながら勉強になります。
Thymeleaf + JAX-RS + DomaをGlassFishで試してみる - 裏紙
JavaDayTokyo2015での寺田さんの発表資料。CDIについてまとまっています。
http://www.oracle.co.jp/jdt2015/pdf/2-2.pdf
今回利用した、@siosioさん作のIntelliJ IDEA Doma Support Plugin
IntelliJ IDEA用のDomaプラグイン作ってみた - しおしお
Doma公式ドキュメント