posts - 431,  comments - 344,  trackbacks - 0
今天遇到一个可笑但又很实际的问题, 比如我有一个user表, 里面的字段为id, name, password等等, 还有一个表user_info表, 里面有id, age, email, address 等等.
但这两张表没有关联字段,也就是说没有外键约束. 但我想在grail中查询两张表, 获取里面的name, password, age, email以及address等等. 条件是两个id相等.
这时候如何做呢??? 目前为止我想到的就是使用Spring中的JdbcTemplate来处理SQL语句:
class User {
 String name
 String password
}

class UserInfo {
    int age
    String email
    String address
}

在controller中写:

def dataSource
    def list = {
      def template = new JdbcTemplate(dataSource)
      def userList = template.queryForList("select ui.name as name, u.password as password, ui.age as age, ui.email as email, ui.address as address  from user u, user_info ui where u.id = ui.id");
      def map = [userList : userList]

      render(view:"list", model:map)
    }


在gsp中只要使用as后面的别名来取对应的值就可以了.

<table>
                    <thead>
                        <tr>
                            <g:sortableColumn property="name" title="Name" />

                            <g:sortableColumn property="password" title="Password" />

                                <g:sortableColumn property="email" title="Emial" />

                                <g:sortableColumn property="age" title="Age" />

                                <g:sortableColumn property="address" title="Address" />

                        </tr>
                    </thead>
                    <tbody>
                    <g:each in="${userList}" status="i" var="user">
                        <tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
                            <td>${user.name}</td>
                            <td>${user.password}</td>
                            <td>${user.email}</td>
                            <td>${user.age}</td>
                            <td>${user.address}</td>
                        </tr>
                    </g:each>
                    </tbody>
                </table>

注意:红色的部分要名字一样, 当然你也可以不使用别名, 直接用原来名字也可以!
posted on 2008-07-18 20:37 周锐 阅读(1377) 评论(0)  编辑  收藏 所属分类: Groovy&Grails

只有注册用户登录后才能发表评论。


网站导航: