2011年9月6日火曜日

ZK Database CRUD を EJB3.1で簡素化


  1. 動機
  2. はZKElection がGlassFish3.01 で動作していたものがNetBeans7.0.1内蔵の3.1.1で動作しないことを調査開始したことだった。MySQL をJNDI コネクションプールで接続しているのですが、コネクションプールの名前が探せないと言うエラーが出たのです。
  3. 為になったサイト
  4. JavaDude ( http://javadude.wordpress.com/ )
    このサイトで、"ZK with EJB3.1 running on GlassFish"というタイトルでREMのプラグインを使用し、JavaEE6 のEJB3.1,JPAでEJB,Databaseアクセスを構成し、global JNDI の使用した数少ないサンプルを見せてくれています。
    ここでの改良点は
    ①JavaDude ではEJBを別プロジェクトで作成し、Webプロジェクトにライブラリとして追加していましたが、その必要はなく、最初からJavaEE6のZKプロジェクトとして作成可能なことを確認できました。
    ②JavaDudeではrendererをapply属性で呼んでいましたが、ここではzul コードの中で、forEach を使用して直接オブジェクトの数をループさせるようにしました。
    ③global JNDI を使用してBlockFacade をcall するコードの NetBeans での自動生成する方法がわかりました。

  5. global JNDI で BlockFacade をcall するコードの NetBeans での自動生成
  6. ①空きスペースで右クリック
    ②コードを挿入を選択
    ③エンタープライズBeanを呼び出し
    ④プロジェクトのリストが現れ、プロジェクトを選択するとその中のEJB が現れるので、
    欲しいものを選択する。
    次に自動生成されたコードを示す。
        private BlockFacade lookupBlockFacadeBean() {
    try {
    Context c = new InitialContext();
    return (BlockFacade) c.lookup("java:global/ElectionEJB/BlockFacade!ejb.election.session.BlockFacade");
    } catch (NamingException ne) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
    throw new RuntimeException(ne);
    }
    }

  7. zul file
  8. z スクリプトで Java コードが内蔵されています。
    <?xml version="1.0" encoding="UTF-8"?>

    <zk xmlns="http://www.zkoss.org/2005/zul">
    <div align="center">
    <window border="normal" width="800px" title="ブロック リスト" >
    <div align="left" style="margin-left:30pt;margin-top:10pt;margin-bottom:10pt">
    <zscript>
    import ejb.election.session.BlockFacade;
    import ejb.election.entity.Block;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    Context context;
    BlockFacade blkdao;
    context = new InitialContext();
    blkdao = (BlockFacade) context.lookup("java:global/ElectionEJB/BlockFacade");
    // BlockFacade blkdao = new BlockFacade();
    List allBlocks = blkdao.findAll();


    public void add(){
    Block newBlk = new Block();
    newBlk.setId(Long.parseLong(cd.value.toString()));
    newBlk.setBlock_name(name.value);
    blkdao.create(newBlk);
    //synchronized data with database
    allBlocks = blkdao.findAll();

    //insert a listBlock into the listbox
    Listitem li = new Listitem();
    li.setValue(newBlk);
    li.appendChild(new Listcell(cd.value.toString()));
    li.appendChild(new Listcell(name.value));
    box.appendChild(li);
    }
    void update(){
    //update database
    Block editBlk = (Block)box.selectedItem.value;
    editBlk.setId(Long.parseLong(cd.value.toString()));
    editBlk.setBlock_name(name.value);
    blkdao.edit(editBlk);

    //update listbox
    List children = box.selectedItem.children;
    ((Listcell)children.get(0)).label = cd.value.toString();
    ((Listcell)children.get(1)).label = name.value;
    }
    void delete(){
    blkdao.remove((Block)box.selectedItem.value);
    box.removeItemAt(box.getSelectedIndex());
    cleargb();

    }
    void move(){
    cd.value = (((Block)box.selectedItem.value).getId()).intValue();
    name.value = ((Block)box.selectedItem.value).getBlock_name();
    }
    void cleargb(){
    cd.value = null;
    name.value = null;
    }
    </zscript>
    <listbox id="box" multiple="true" rows="12"
    onSelect="move()">
    <listhead>
    <listheader label="ブロックコード" width="40px" />
    <listheader label="ブロック名" width="200px" />
    </listhead>
    <listitem forEach="${allBlocks}" value="${each}">
    <listcell label="${each.id}" />
    <listcell label="${each.block_name}" />
    </listitem>
    </listbox>
    <groupbox>
    <caption label="選挙区" />
    ブロックコード: <intbox id="cd" cols="1" />
    ブロック名: <textbox id="name" cols="20" />

    <div align="right" style="margin-left:30pt;margin-top:10pt;margin-bottom:10pt">
    <button label="追加" width="50px" height="24px" onClick="add()" />
    <button label="更新" width="50px" height="24px" onClick="update()" />
    <button label="削除" width="50px" height="24px" onClick="delete()" />
    </div>
    </groupbox>
    </div>
    </window>
    </div>
    </zk>



  9. facade コード
  10. abstract facade を拡張します。
    package ejb.election.session;

    import ejb.election.entity.Block;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;

    @Stateless
    public class BlockFacade extends AbstractFacade {
    @PersistenceContext(unitName = "ElectionEJBPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
    return em;
    }

    public BlockFacade() {
    super(Block.class);
    }

    }

  11. entity コード
  12. 自動生成します。
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package ejb.election.entity;

    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

    /**
    *
    * @author stera
    */
    @Entity
    public class Block implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String block_name;

    public String getBlock_name() {
    return block_name;
    }

    public void setBlock_name(String block_name) {
    this.block_name = block_name;
    }

    public Long getId() {
    return id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    @Override
    public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
    }

    @Override
    public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Block)) {
    return false;
    }
    Block other = (Block) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
    return false;
    }
    return true;
    }

    @Override
    public String toString() {
    return "ejb.election.NewEntity[ id=" + id + " ]";
    }

    }

0 件のコメント: