论坛首页 Java企业应用论坛

根据select sql中的字段名生成一个JavaBean,bean中包含所有字段的Get方法

浏览 16258 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (6)
作者 正文
   发表时间:2010-04-01   最后修改:2010-04-01

例如我有一个这样的sql:

select username, password from users

 我想在select结束后,通过ResultSet中的字段名生成一个JavaBean,其代码大概如下:

public class Record{
   //生成这个方法,get后返回sql中结果集的username字段值
   public String getUsername(){}
   //生成这个方法,get后返回sql中结果集的password字段值
   public String getPassword(){}
}

关键在于:这个JaveBean是动态的,Get方法因应sql字段不同而不同

曾经记得在Hibernate中广泛使用这种生成字节码,动态化Class的应用,敢问各位高手,是否知道如何实现,请赐教!!

 

补充一下应用场景:

select 后,生成的这个Record,我是用在Jsp的 el 表达式中:

<h1>UserName:${record.Username}<h1>
<h1>Password:${record.Password}<h1>

 这样就避免每个数据库表都写一个JavaBean了,不知我这样的想法是否可行,如有什么性能问题或其他担心,敬请指正!

感谢!!

   发表时间:2010-04-01  
用Hibernate的朋友帮忙看看
0 请登录后投票
   发表时间:2010-04-01  
可以通过查询封装为List<Map<String,Object>> 形式的数据。前面的页面也支持
${map.name}的形式的。
2 请登录后投票
   发表时间:2010-04-01  
hibernate 支持 select new
select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat

或者

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

或者

select new list(mother, offspr, mate.name)
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr

0 请登录后投票
   发表时间:2010-04-01  
wgx19830922 写道
可以通过查询封装为List<Map<String,Object>> 形式的数据。前面的页面也支持
${map.name}的形式的。

嗯,这个是一个方法,谢谢,但我还是想知道有没有办法能实现我原来说的效果
0 请登录后投票
   发表时间:2010-04-01  
hypercube1024 写道
hibernate 支持 select new
select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat

或者

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

或者

select new list(mother, offspr, mate.name)
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr



搞错了,我不用Hibernate,但记得Hibernate有这样的功能而已
0 请登录后投票
   发表时间:2010-04-01  
apache 有一个DynaBean来自Jakata的Common-beanUtil包,这个类就是动态的。或许能帮助你。
0 请登录后投票
   发表时间:2010-04-01  
封装一个动态JavaBean 不用每个都写
0 请登录后投票
   发表时间:2010-04-01  
wgx19830922 写道
可以通过查询封装为List<Map<String,Object>> 形式的数据。前面的页面也支持
${map.name}的形式的。


同意,这样可以在复杂性和灵活性上作出很好的权衡。这种方式应该被提倡并推广。
0 请登录后投票
   发表时间:2010-04-01  
freej 写道
wgx19830922 写道
可以通过查询封装为List<Map<String,Object>> 形式的数据。前面的页面也支持
${map.name}的形式的。


同意,这样可以在复杂性和灵活性上作出很好的权衡。这种方式应该被提倡并推广。

同意,感谢各位的回贴,刚才测试了一下,发现这种方式最直观,最灵活,感谢wgx19830922,非常感谢!
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics