hibernate中SQLQuery的addEntity()和setResultTransformer方法
如果使用原生sql语句进行query查询时,hibernate是不会自动把结果包装成实体的。所以要手动调用addEntity(Class class)等一系列方法。
如session.createSQLQuery(sql).addEntity(Class class);注意hibernate3.0.5不支持,单个参数的addEntity方法
另外,hibernate3.2可以对原生sql 查询使用ResultTransformer。这会返回不受Hibernate管理的实体。
session.createSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
.setResultTransformer(Transformers.aliasToBean(CatDTO.class))
或setResultTransformer(new AliasToBeanResultTransformer (CatDTO.class))
上面的查询将会返回CatDTO的列表,它将被实例化并且将NAME和BIRTHDAY的值注射入对应的属性或者字段。
http://bbs.xml.org.cn/blog/more.asp?name=lhwork&id=15351
但必须注意,对每一个列都必须addScalar("列名")
既然如此,
那么setResultTransformer与addEntity的区别是什么呢?一个区别是前者支持查任意的列,后者必须用select * from users的形式或select {a.*},{b.*} from a,b where ....。
String hql = "select {cdc.*} " +
"from ta_car_dept cd," +
"ta_cardept_desc cdc " +
"where cd.s_code in ( "+sCode+" )" +
" and cd.type = 1" +
" and cdc.lan_id = 1" +
" and cd.auto_type_id = cdc.auto_type_id ";
List list = session.createSQLQuery(hql).addEntity("cdc", TaCarDeptDesc.class).list();
===========
String hql = "select cd.s_code ,cdc.auto_name " +
"from ta_car_dept cd," +
"ta_cardept_desc cdc " +
"where cd.s_code in ( "+sCode+" )" +
" and cd.type = 1" +
" and cdc.lan_id = 1" +
" and cd.auto_type_id = cdc.auto_type_id ";
List list = session.createSQLQuery(hql).addScalar("s_code", Hibernate.STRING).addScalar("auto_name", Hibernate.STRING).list();
Spring MVC and AJAX with JSON
You can use json-lib-ext-spring. There are other libs, this is the one I found. If you know or use another one, please leave a comment with the library name.
Do not forget to download Json-lib and its dependencies.
Now you have to configure your XML files:
Create a views.xml file under WEB-INF folder and paste the following code into it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<? xml version = "1.0" encoding = "UTF-8" ?> xsi:schemaLocation= "http://www.springframework.org/schema/beans < bean name = "jsonView" class = "net.sf.json.spring.web.servlet.view.JsonView" /> </ beans > |
Add this config to you spring configuration file:
1
2
3
4
5
6
7
8
9
|
<!-- json --> < bean id = "xmlFileViewResolver" class = "org.springframework.web.servlet.view.XmlViewResolver" > < property name = "location" > < value >/WEB-INF/views.xml</ value > </ property > < property name = "order" > < value >1</ value > </ property > </ bean > |
Make sure to set the order if you are using any other view resolvers.
Now you just have to use “jsonView” as the viewname and the model will be converted to JSONbefore being sent back to the client:
1
|
return new ModelAndView( "jsonView" , modelMap); |
Here is an example:
1
2
3
4
5
6
7
8
|
public ModelAndView getColumnsJson(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,Object> modelMap = new HashMap<String,Object>( 2 ); modelMap.put( "rows" , service.generateColumns()); return new ModelAndView( "jsonView" , modelMap); } |
Happy coding!
Spring MVC 整合 JSON 视图
Jackson转换Java对象
1、 jackson有专门的视图MappingJacksonJsonView,只需用配置这个视图就可以完成转换json了。使用jackson需要添加如下jar包:
如果你对Jackson转换Java对象还没有什么了解的话,你可以参考:
For cnblogs:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
For csdn:http://blog.csdn.net/IBM_hoojo/archive/2011/04/22/6340762.aspx
2、 然后需要在dispatcher.xml中添加视图配置,配置如下:
<bean name="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="encoding">
<value type="org.codehaus.jackson.JsonEncoding">UTF8value>
property>
<property name="contentType" value="text/html;charset=UTF-8"/>
bean>
3、 将Java对象转换JSON
package com.hoo.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hoo.entity.Account;
import com.hoo.entity.Brithday;
import com.hoo.entity.User;
/**
* function:用MappingJacksonJsonView视图和Jackson转换Json
* @author hoojo
* @createDate 2011-4-28 下午04:52:23
* @file JacksonJsonViewController.java
* @package com.hoo.controller
* @project SpringMVC4View
* @blog http://blog.csdn.net/IBM_hoojo
* @email [email protected]
* @version 1.0
*/
@Controller
@RequestMapping("/jackson/view")
public class JacksonJsonViewController {
/**
* function:转换普通Java对象
* @author hoojo
* @createDate 2011-4-28 下午05:14:18
* @return
*/
@RequestMapping("/doBeanJsonView")
public ModelAndView doBeanJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonView");
User user = new User();
user.setAddress("china GuangZhou");
user.setAge(23);
user.setBrithday(new Date());
user.setName("jack");
user.setSex(true);
Account bean = new Account();
bean.setAddress("北京");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
Brithday day = new Brithday();
day.setBrithday("2010-11-22");
bean.setBrithday(day);
mav.addObject(bean);
return mav;
}
}
上面使用了刚才我们配置的jsonView视图,通过这个视图就可以将ModelAndView中的数据转换成JSON数据。
在浏览器中请求:http://localhost:8080/SpringMVC4View/jackson/view/doBeanJsonView.do
结果如下:
{"account":{"address":"北京","name":"haha","id":1,"email":"email","brithday":{"brithday":"2010-11-22"}}}
4、 转换Map到JSON
/**
* function:转换Map集合
* @author hoojo
* @createDate 2011-4-28 下午05:14:33
* @return
*/
@RequestMapping("/doMapJsonView")
public ModelAndView doMapJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonView");
User user = new User();
user.setAddress("china GuangZhou");
user.setAge(23);
user.setBrithday(new Date());
user.setName("jack");
user.setSex(true);
Map
map.put("user", user);
map.put("success", true);
mav.addObject(map);
mav.addObject("title", "ViewController doBeanJsonView");
return mav;
}
在WebBrowser中请求:http://localhost:8080/SpringMVC4View/jackson/view/doMapJsonView.do
结果如下:
{"hashMap":{"success":true,"user":{"address":"china GuangZhou","name":"jack","age":23,"sex":true,"brithday":1303982296953}},
"title":"ViewController doBeanJsonView"}
5、 转换List到JSON
/**
* function:转换List集合
* @author hoojo
* @createDate 2011-4-28 下午05:14:54
* @return
*/
@RequestMapping("/doListJsonView")
public ModelAndView doListJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonView");
List<User> list = new ArrayList<User>();
for (int i = 0; i < 3; i++) {
User user = new User();
user.setAddress("china GuangZhou#" + i);
user.setAge(23 + i);
user.setBrithday(new Date());
user.setName("jack_" + i);
user.setSex(true);
list.add(user);
}
mav.addObject(list);
return mav;
}
在浏览器中请求http://localhost:8080/SpringMVC4View/jackson/view/doListJsonView.do
结果如下:
{"userList":[{"address":"china GuangZhou#0","name":"jack_0","age":23,"sex":true,"brithday":1303982399265},
{"address":"china GuangZhou#1","name":"jack_1","age":24,"sex":true,"brithday":1303982399265},
{"address":"china GuangZhou#2","name":"jack_2","age":25,"sex":true,"brithday":1303982399265}]}
总结,spring对jackson提供了专门的视图,整合起来也比较方便。而且jackson也比较简单易用。
七、 JSON-lib转换Java到JSON
1、 Spring没有提供JSON-lib的view视图,不过没有关系。我们可以自己扩展一个,只需用继承AbstractView类,实现里面的方法就可以了。首先你需要了解JSON-lib,如果你还不了解JSON-lib的话,建议阅读:
For cnblogs: http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html
For csdn: http://blog.csdn.net/IBM_hoojo/archive/2011/04/21/6339246.aspx
然后你需要在工程中添加如下jar文件:
2、 因为Spring没有提供view,我们需要自己实现一个。代码如下:
package com.hoo.veiw.xml;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;
/**
* function:扩展AbstractView 实现JSON-lib视图
* @author hoojo
* @createDate 2011-4-28 下午05:26:43
* @file MappingJsonlibVeiw.java
* @package com.hoo.veiw.xml
* @project SpringMVC4View
* @blog http://blog.csdn.net/IBM_hoojo
* @email [email protected]
* @version 1.0
*/
public class MappingJsonlibVeiw extends AbstractView {
public static final String DEFAULT_CONTENT_TYPE = "application/json";
public static final String DEFAULT_CHAR_ENCODING = "UTF-8";
private String encodeing = DEFAULT_CHAR_ENCODING;
public void setEncodeing(String encodeing) {
this.encodeing = encodeing;
}
private SetrenderedAttributes;
private JsonConfig cfg = null;
public void setCfg(JsonConfig cfg) {
this.cfg = cfg;
}
public MappingJsonlibVeiw() {
setContentType(DEFAULT_CONTENT_TYPE);
}
@Override
protected void renderMergedOutputModel(Map
HttpServletResponse response) throws Exception {
model = filterModel(model);
response.setCharacterEncoding(encodeing);
PrintWriter out = response.getWriter();
if (cfg == null) {
out.print(JSONSerializer.toJSON(model));
} else {
out.print(JSONSerializer.toJSON(model, cfg));
}
}
/**
* Filters out undesired attributes from the given model.
* Default implementation removes {@link BindingResult} instances and entries not included in the {@link
* #setRenderedAttributes(Set) renderedAttributes} property.
*/
protected Map
Map
SetrenderedAttributes =
!CollectionUtils.isEmpty(this.renderedAttributes) ? this.renderedAttributes : model.keySet();
for (Map.Entry
if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
}
上面的代码不是很复杂,首先我们设置contentType,这个属性在AbstractView这个父类中有setter方法可以完成设置。
然后就是默认的编码格式,这个编码格式设置到response上。默认UTF-8编码。在renderMergedOutputModel方法中可以看到设置。
第三就是filterModule方法,这个方法是得到ModelAndView中我们添加对象,过滤掉BindingResult的信息。
最后就是renderMergedOutputModel方法,这个方法最为核心,但也很简单。过滤model获得要转换的model数据,设置response编码格式。利用response的Writer输出JSON信息,通过JSONSerializer转换Java到JSON。
3、 在dispatcher.xml中配置jsonlibView这个视图
<-- 自定义JSONlib的json视图 -->
<bean name="jsonlibView" class="com.hoo.veiw.xml.MappingJsonlibVeiw">
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="encodeing" value="gbk"/>
bean>
4、 转换普通Java对象
package com.hoo.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hoo.entity.Account;
import com.hoo.entity.Brithday;
import com.hoo.entity.User;
/**
* function:
* @author hoojo
* @createDate 2011-4-28 下午05:58:02
* @file JsonlibMappingViewController.java
* @package com.hoo.controller
* @project SpringMVC4View
* @blog http://blog.csdn.net/IBM_hoojo
* @email [email protected]
* @version 1.0
*/
@Controller
@RequestMapping("/jsonlib/view")
public class JsonlibMappingViewController {
/**
* function:转换普通Java对象
* @author hoojo
* @createDate 2011-4-28 下午05:14:18
* @return
*/
@RequestMapping("/doBeanJsonView")
public ModelAndView doBeanJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonlibView");
User user = new User();
user.setAddress("china GuangZhou");
user.setAge(23);
user.setBrithday(new Date());
user.setName("jack");
user.setSex(true);
Account bean = new Account();
bean.setAddress("北京");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
Brithday day = new Brithday();
day.setBrithday("2010-11-22");
bean.setBrithday(day);
mav.addObject(bean);
return mav;
}
}
在WebBrowser中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doBeanJsonView.do
结果如下:
{"account":{"address":"北京","brithday":{"brithday":"2010-11-22"},"email":"email","id":1,"name":"haha"}}
5、 转换Map到JSON
/**
* function:转换Map集合
* @author hoojo
* @createDate 2011-4-28 下午05:14:33
* @return
*/
@RequestMapping("/doMapJsonView")
public ModelAndView doMapJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonlibView");
User user = new User();
user.setAddress("china GuangZhou");
user.setAge(23);
user.setBrithday(new Date());
user.setName("jack");
user.setSex(true);
Map
map.put("user", user);
map.put("success", true);
mav.addObject(map);
mav.addObject("title", "ViewController doBeanJsonView");
return mav;
}
在WebBrowser中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doMapJsonView.do
结果如下:
{"hashMap":{"success":true,"user":{"address":"china GuangZhou","age":23,
"brithday":{"date":28,"day":4,"hours":18,"minutes":20,"month":3,"seconds":8,
"time":1303986008703,"timezoneOffset":-480,"year":111},"name":"jack","sex":true}},
"title":"ViewController doBeanJsonView"}
发现时间被分解成一个对象了,这里需要用JSONConfig的JsonValueProcessor将brithday过滤下,然后用SimpleDateFormate进行格式转换。
6、 转换List集合
/**
* function:转换List集合
* @author hoojo
* @createDate 2011-4-28 下午05:14:54
* @return
*/
@RequestMapping("/doListJsonView")
public ModelAndView doListJsonView() {
System.out.println("#################ViewController doBeanJsonView##################");
ModelAndView mav = new ModelAndView("jsonlibView");
List<User> list = new ArrayList<User>();
for (int i = 0; i < 3; i++) {
User user = new User();
user.setAddress("china GuangZhou#" + i);
user.setAge(23 + i);
user.setBrithday(new Date());
user.setName("jack_" + i);
user.setSex(true);
list.add(user);
}
mav.addObject(list);
return mav;
}
在浏览器中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doListJsonView.do
结果如下:
{"userList":[{"address":"china GuangZhou#0","age":23,"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,
"time":1303988574328,"timezoneOffset":-480,"year":111},"name":"jack_0","sex":true},
{"address":"china GuangZhou#1","age":24,"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,
"time":1303988574328,"timezoneOffset":-480,"year":111},"name":"jack_1","sex":true},{"address":"china GuangZhou#2","age":25,
"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,"time":1303988574328,"timezoneOffset":-480,"year":111},
"name":"jack_2","sex":true}]}