An Easier Java ORM(3) 実装の詳細を詰める

http://www.javalobby.org/articles/activeobjects/の日本語訳です。<< An Easier Java ORM(2) 教訓をJavaに活かす - 目次に戻る - An Easier Java ORM(4) 複雑な問い合わせ >>

実装の詳細を詰める - Fleshing Out the Implementation

これらのインタフェースだけではORMを作ることはできません。データベースアクセスはgetterやsetter意外にも多くの要素があります。しかしすでに述べたように、APIの実装という目標の指針のために、考え方をコードで記述すればよいのです。これまでにフレームワークについて分かっていることを、(インタフェースと動的プロキシに基づいて)それっぽいコードとして思い描くければよいのです。

A few random interfaces does not an ORM make. There are far more things to database access than just getters and setters. But as before, we can write concept code to guide our efforts in implementing the API. Given what we know about the framework so far (based on interfaces and dynamic proxies), we should be able to envision some plausible code:

public interface Company extends Entity {  
    public String getName();  
    public void setName(String name);  
      
    public String getTickerSymbol();  
    public void setTickerSymbol(String tickerSymbol);  
      
    @OneToMany  
    public Person getPeople();  
}  
// Personも同様に定義されているものとする assume Person is defined similarly  
  
EntityManager manager = new EntityManager("jdbc:mysql://localhost/test", "user", "password");  
  
Company companies = manager.find(Company.class);  
for (Company c : companies) {  
    System.out.println(c.getName());  
      
    for (Person p : c.getPeople()) {  
        p.setFirstName("Joe");  
        p.setAge(8);  
        p.save();  
    }  
}  
  
Company dzone = manager.find(Company.class, "name = DeveloperZone")[0];  
  
Person me = manager.create(Person.class);  
me.setFirstName("Daniel");  
me.setLastName("Spiewak");  
me.setCompany(dzone);  
me.save();  

Compamyインタフェースをちょっと手を加えたことがわかります。関連を扱えるようになったのです。しかし、このサンプルではさらに興味深いプロトタイピングをしています。EntityManagerクラスを取り入れたのです。

You'll notice that we have added to the Company interface slightly: we're now handling relations. However, the bulk of the interesting prototyping is being done farther along in the sample. We've now introduced the EntityManager class.

われわれの新たなORMが興味深い動作をするには、EntityManagerは非常に重要です。これによってデータベース接続が確立され、動的プロキシが作られ、関係するインタフェースの動的インスタンスにラップされます。さらにここでfind()のような大事な問い合わせ操作を扱います。Javaのインタフェースはクラスメソッドを持てないので、ActiveRecordと異なりfind()やその仲間をEntity上位インタフェースの一部にすることはできません。しかし、EntityManager#find(…)文法を十分シンプルに保ってれば、それほど大きな違いにはならないでしょう。

EntityManager is the focal point for all of the interesting activity in our new ORM. This is where the database connection is established, it's where the dynamic proxy is created and wrapped into dynamic instance of the relevant interfaces. Here also, we have the handling of interesting query operations like find(). Unlike ActiveRecord, we can't put find() and friends as part of the Entity super-interface since interfaces in Java cannot contain class methods. However, if we keep the EntityManager#find(…) syntax simple enough, it shouldn't make too much of a difference.

<< An Easier Java ORM(2) 教訓をJavaに活かす - 目次に戻る - An Easier Java ORM(4) 複雑な問い合わせ >>