但這兩張表沒有關聯字段,也就是說沒有外鍵約束. 但我想在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>