Java JPA

摘要:Java JPA

這裡我很偷懶的去實作Java JPA,有點類似Hibernate或EntifyFramework,

他就是一個ORM的其中一個方案,

而我偷懶的使用palyframework中解壓縮後,放在playframework\play\framework\lib中的所有jar檔全部複製後

並且建立META-INF 及在裡面建立persistence.xml,應該就可以跑起來了

而persistence.xml就參考

http://www.dotblogs.com.tw/newmonkey48/archive/2012/02/14/69207.aspx 中的資料設定

再來是建立Model ,及撰寫JPAUtils

都可以從網路上抄到

http://caterpillar.onlyfun.net/Gossip/EJB3Gossip/FirstLocalJPA.html

 

這裡我要另外撰寫萬用型的BaseDao 並在裡面撰寫insert update delete 及select single note及select list

只要Model的Object有案照規則撰寫的話,

取得屬性使用的是get ,set ,且私有欄位的名稱有底線的話,以底線做分割,開頭為大寫組合的話

例:my_name →getMyName、setMyName,這樣的方式的時候。

我就可以使用這個萬用型BaseDao,當放入一般的物件,會根據物件的內容不為null的話,則設為等號條件。

以減少大量的SQL程式碼

裡頭使用了不少泛型、反射的技術處理。


package com.project.dao;

import javax.persistence.*;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import java.lang.reflect.Method;
import java.util.*;

public class BaseDao {

    public EntityManager getEntifyManager()
    {
          return  JPAUtil.getEntityManagerFactory().createEntityManager();
    }

    public  T getResult(Class c,String primary_key,Long primary_value)
    {
        EntityManager em =this.getEntifyManager();
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
        Root mission = criteriaQuery.from(c);
        EntityType TiepMission_ = mission.getModel();
        Predicate testCondition = criteriaBuilder.equal(mission.get(TiepMission_.getSingularAttribute(primary_key, Long.class)),primary_value);
        criteriaQuery.where(testCondition);
        CriteriaQuery select = criteriaQuery.select(mission);
        TypedQuery typedQuery = em.createQuery(select);
        typedQuery.setFirstResult(0);
        typedQuery.setMaxResults(1);
        List list=  (List)typedQuery.getResultList();
        if(list.size() > 0 )
            return (T)list.get(0);
        else 
            return null;
    }

    public   boolean  exists(T info)
    {
        Class c =info.getClass();
        List list=list(c,info,0,1);
        if(list.size()>0)
           return true;
        else
           return false;
    }

    public  T getResult(Object info)
    {
        Class c =((T)info).getClass();
        List list=list(c,info,0,1);
        if(list.size()>0)
           return (T)list.get(0);
        else
           return null;
    }

    public  List list(Object info)
    {
        int first_num = 0 ;
        int max_num = 10000;
        List listAll = new ArrayList();
         List listA = null;
        Class c = info.getClass();
        do
        {
            listA =list(c,info,first_num,max_num);
            if(listA.size()>0)
            {
                 listAll.addAll(listA);
            }
            first_num += max_num;
        }while(listA.size() > 0 );
        return listAll;
    }

    public  List list(Object info,int first_num,int max_num)
    {
            Class c = info.getClass();
            return    list( c, info, first_num, max_num)   ;
    }

    public  List list(Class c,Object info,int first_num,int max_num)
    {
        EntityManager em =this.getEntifyManager();
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
        Root template = criteriaQuery.from(c);
        EntityType Template_ = template.getModel();

        Predicate condition = null;
        Predicate condition_temp = null;

        Method m[] = c.getDeclaredMethods();
        Object[] args = null;
        for (int i = 0; i < m.length; i++)
        {
            try
            {
                if(m[i].getName().startsWith("get"))
                {
                    String name_temp = m[i].getName().substring(3);
                    String name = "";
                    StringBuffer buffer = new StringBuffer();
                    for(int j=0;j select = criteriaQuery.select(template);
        TypedQuery typedQuery = em.createQuery(select);
        typedQuery.setFirstResult(first_num);
        typedQuery.setMaxResults(max_num);
        List list=  (List)typedQuery.getResultList();
        List listT = new ArrayList();
        if(list.size()>0)
        {
           for(Object o :list)
           {
             listT.add((T)o);
           }
        }
        return listT;
    }


    public boolean update(Object info){
        EntityManager em = this.getEntifyManager();
        boolean ret = true;
        try{
            em.getTransaction().begin();
            em.merge(info);
            em.getTransaction().commit();
        }catch (Exception ex ){
            ret = false;
            log.error( ex );
        }finally {
            {
                em.close();
            }
        }
        return ret;
    }

    public void insert(Object info){
        EntityManager em = this.getEntifyManager();
        try{
            em.getTransaction().begin();
            em.persist(info);
            em.getTransaction().commit();
        }catch (Exception ex ){
            log.error( ex );
        }finally {
            {
                em.close();
            }
        }
    }

    public void init(Object info)
    {
        Class c = info.getClass();
        Method m[] = c.getDeclaredMethods();

        for (int i = 0; i < m.length; i++)
        {
            try
            {
                if(m[i].getName().startsWith("set"))
                {
                    String method_name =m[i].getName().replaceFirst( "set","get" );
                    Method mg = c.getMethod(method_name);
                    Class rt =  mg.getReturnType();
                    //args = new Object[]{ };
                    Long l = new Long( 1 );
                    Class lc = l.getClass();
                    if(rt.toString().contains("List")) continue;

                    if(rt.toString().contains( "Long" ))
                        m[i].invoke( info,new Long(0));
                    else
                        m[i].invoke( info,rt.newInstance());
                }
            }catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}