Hibernate示例需要多个1到多个映射

时间:2013-04-05 18:32:58

标签: java hibernate

一直在寻找并找不到这样的例子..我是Hibernate的新手,但可以创建一个单级JSON ......如果我使用预准备语句和多个数组,我可以实现这一点,但我可以使用Hibernate和createSQLQuery让它工作。

我需要创建多个1到多个级别的JSON,即:

{       “成功”:是的,       “数”:1,       “信息”: ””,       “数据”:[

{                   “inProgress”:假的,                   “item”:“372”,                   “时间”:“09:00”,                   “日期”:“2013-03-22”,                   “状态”:“inProgress”,

“标签”:[                         “第一”,                         “第二”,                         “第三”,                         “持续”                   ],

“item”:[                         {                               “等级”:“第一”,                               “时间”:“6:36:05”,

“详情”:[                                     {                                           “间隔”:“1:31.63”                                     },

{                                           “间隔”:“1:32.63”                                     },

{                                           “间隔”:“1:35.99”                                     },

{                                           “间隔”:“1:38.63”                                     }                               ]                         }                   ]             }       ] }

因此,多个项目中可能存在多个细节,并且有多个标签。

            Query query = session.createSQLQuery(sql)
                    .addScalar("item",Hibernate.STRING)
                    .addScalar("time",Hibernate.STRING)
                    .addScalar("date",Hibernate.STRING)
                .addScalar("futureProgression",Hibernate.STRING) 
            .setResultTransformer(Transformers.aliasToBean(ABC.class));

            resultList = query.list();

我可以创建顶级,但我无法弄清楚如何使用.addEntity将实体插入该级别......

任何人都有一个方便的例子吗?

谢谢, 杰夫

2 个答案:

答案 0 :(得分:0)

通过以下链接查看如何定义与映射的1对多关系

http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/example-parentchild.html

如果使用一组较低级别的对象持久保存顶级对象,hibernate将负责在表格中创建顶级和较低级别的条目。

session.save(父)

答案 1 :(得分:0)

如果你在调用query.createSQLQuery(String sql)时使用query.list(),它会返回一个列表,每个列表元素都有一个对象数组[以数据库的方式用另一种语言行]。

如果您想从hibernate使用JSON,那么有一个示例:

import org.json.*;
//.... your imports here :
//

public class JSONObjectRetriever{

    public JSONObject getDataByID(){
        ArrayList<Object[]> resultList = HibernateManager.getItems();
        ArrayList<Item> finalJsonList = new ArrayList<Item>();

        if(resultList != null)
        {
           Iterator<Object[]> it = resultList.iterator();
           while(it.hasNext())
           {
               Object [] obj = it.next(); // fetching one row from the database.

               //---- Deprecated ...
               //finalJsonList.add(obj[0]);
               //finalJsonList.add(obj[1]);
               //finalJsonList.add(obj[2]);

               //---- the new fragment is : How Add Label to the values :
               //------------------------------------

               finalJsonList.put("Item ID", obj[1]);
               finalJsonList.put("Item Name", obj[2]);
               finalJsonList.put("Item Price", obj[3]);

           }
           JSONArray jsonArray = new JSONArray(catList);
       HashMap<String, JSONArray> map = new HashMap<String, JSONArray>();

       map.put("finalJsonList", jsonArray);
       JSONObject jsonObject = new JSONObject(map);
       return jsonObject;
        }
        else{
           return null;
        }
    }
}

现在Hibernate Manager将是这样的:

public class HibernateManager{

   private SessionFactory sessionFactory;
   static{
       //initialize the session factory here.....
   }

   public static List getItems(){
     String sql = "...."; // put your sql here full String;
     Session session = sessionFactory.openSession();
     session.beginTransaction();
     Query query = session.createSQLQuery(sql);
     List resultList = query.list();
     session.getTransaction().commit();
     return resultList;
   }
}

然后你需要Servlet并定义响应类型是application / json 在这个servlet中:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    JSONObjectsRetriever jR = new JSONObjectsRetriever();
    JSONObject jsonObj = jR.getDataByID();

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");

    PrintWriter writer = response.getWriter();
    //System.out.println(jsonObj);
    writer.print(jsonObj);
    writer.flush();
    writer.close();
}

然后在你的ajax技巧或jQuery中,你可以在回调方法中使用这个servlet来取代你想要的值:在这个例子中我使用了jquery ....

$.ajax(
{
      url : CONTEXT_ROOT+"ItemsJSONFromHibernateServlet",
  type : "GET",
  dataType : "json",
      data : {"param1": value, "param2" : value2, ... etc}, //if you are like to send parameters to the database
  success: function(data){
         // this will return JSON Object do what do you like here ...

         //Iterating through JSON will be like this :

        for (var key in data) 
        {
          if (data.hasOwnProperty(key))
          {
        //alert(key + " -> " + data[key]);
        var subData = data[key];
        //alert(subData.ID+"Before");
        for(var j=0; j < subData.length; j++)
            {
       //alert(subData[j].Key);
       if(subData[j].Key == val)
               {
         alert(subData[j].Value);
         break;
           }
             }
       }
    }
      },
      error: function(jqHXR){
         // to handle errors
      }
});

我希望这有帮助......

~Ahmad A. Taha