听,如果您query.createSQLQuery(String sql)
在调用时使用query.list()
它将返回一个列表,每个列表元素都有对象数组 [来自数据库的行,用另一种语言]。
如果您喜欢从休眠中使用 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;
}
}
}
现在休眠管理器将是这样的:
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 并定义这个 servlet 里面的响应类型是 application/json :
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
}
});
我希望这有帮助......
〜艾哈迈德·塔哈