JPA(EclipseLink-JPA)を用いたDBアクセス(のはじめの一歩)
MementoWeaver開発記(8)
前回まででEntityの生成を(仮に)行ってみたので、今回はJPA経由でのDBアクセスを実装してみる。
InstallProcessing に以下の記述を追加(抜粋)
EntityManager em = Persistence.createEntityManagerFactory("MyDB").createEntityManager(); (snip) Material materialEntity = new Material(); materialEntity.setMaterialId(timestamp); materialEntity.setCreatedYear(2000); materialEntity.setCreatedMonth(12); materialEntity.setMaterialType(suffix); materialEntity.setMaterialState("1"); em.persist(materialEntity);
実行してみたが案の定エラーの山。以下に、原因と対応を列挙する。
エラーメッセージ:No Persistence provider for EntityManager named MyDB
EntityManagerに与えた"MyDB"と言う名前を知らないと言われる。
ここは単なる勘違いでDB名を与えるのではなく、persistence.xmlのpersistence-unit の名称("MementoWeaver")を与えなければならない。
エラーメッセージ:Unable to acquire a connection from driver [null], user [null] and URL [null]. (略)
略さないメッセージは、Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL.
Check your login, persistence.xml or sessions.xml resource.
The jdbc.driver property should be set to a class that is compatible with your database platform.
ドライバもURLも確かに指定していない。persistence.xmlを見直しているとConnectionタブにそれらしきものがある。
Transaction TypeをRESOURCE LOCALに、Driverなどはpopulate from connection... リンクから設定しなおす。
エラーメッセージ:クラスローダー sun.misc.Launcher$AppClassLoader@709fa12f を使用してデータベース 'C:\Users\kazyury\MyDB' を始動できません。詳しくは、次の例外を参照してください。
エラーメッセージ:ERROR 42Y07: スキーマ 'TEST' は存在しません
確かにDerbyに接続するときはTestユーザーで接続することにしていたので、デフォルト・スキーマとして'TEST'を利用しようとしている。
この件について調べてみた限りの解決策としては以下が考えられる。
- DB接続ユーザーをMWにする(又はDerbyのスキーマをTESTにする)
- 今回はJPAプロバイダとしてEclipseLinkを使用しており、eclipselink-orm.xmlでpersistence-unit-metadata/persistent-unit-defaults/schema を設定する(eclipselink-orm.xml Schema Reference | EclipseLink 2.4.x Java Persistence API (JPA) Extensions Reference)。
- 各エンティティのアノテーションにSCHEMA="MW"を追加する。
今回はとりあえず案3)で回避。本来は案1か案2が良いかな?
その後
DB設計のデータ型がセンス無かったりしてごちゃごちゃとJavaを修正。
最終的にはなんとかpersist(Insert)まで通った。
上記のコードでダミーの文字列を適当に設定している箇所などを修正し、GitHubへコミット。