1 プロジェクト作成
- [ファイル]-[新規プロジェクト]
- [Maven]-[Webアプリケーション] で[次へ]
- プロジェクト名など必須項目に任意の値を入れて[次へ]
- GlassFish, JavaEE7Web を選択して[終了]
- pomを編集してビルド:javaee-web-apiをjavaee-api, maven-compilerの1.7を1.8
2 JPA関連を自動生成
- entity, persistance.xml生成
-- プロジェクト右クリック-[新規]-[DB~Entity]で[次へ]
-- データソースの接続先、表を指定して[次へ]
-- デフォルト値(パッケージ等、必要に応じて変更)で[終了]
-- entity, persistance.xml が自動生成 - Dao生成
-- プロジェクト右クリック-[新規]-[EJB]-[Entity~SessionBean]で[次へ]
-- Entity を指定して[次へ] -- デフォルト値(パッケージ等、必要に応じて変更)で[終了]
-- Dao(Facade)が自動生成 - Service生成
-- プロジェクト右クリック-[新規]-[EJB]-[SessionBean]で[次へ]
-- EJB名、パッケージを指定して[終了]
-- 作られたクラスに Dao を @Inject して private 変数作成 -- Dao のメソッド実行するメソッドを作成
3 JPA Entity以外の使用
public class Test {
private String name;
private long count;
public Test(String name, long count){
this.name = name;
this.count = count;
}
public Test(){}
// 以下、getter,setter
List<Test> tests = em.createQuery(
"select new xxx.xxx.Test(s.name, count(s)) "
+ "from Main m join Sub s on m.id = s.mainId group by s",
Test.class
).getResultList();
for(Test test : tests) {
System.out.println(test.getName() + ":" + test.getCount());
}
4 AOPの設定
アノテーション作成
@InterceptorBinding
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Priority(Interceptor.Priority.APPLICATION + 20)
public @interface AopMethod{
}
AOP処理実装
@Interceptor
@Dependent
@AopMethod
public class AopInterceptor implements Serializable{
@AroundInvoke
public Object invoke(InvocationContext ic) throws Exception{
try{
return ic.proceed();
}catch(Exception ex){
Logger logger = Logger.getLogger(ic.getTarget().getClass().getSuperclass().getName());
logger.log(Level.SEVERE, "error", ex);
return null;
}
}
}
AOPを設定
@AopMethod
public void subCalc(){
result = calcLogic.sub(param1, param2);
}
参考