1
多个域对象我非常中的Grails一个新手。我正在学习一个基本的CRUD操作。这里我有2个域对象Person和Address。每个人只需要表单提交到Grails中
所以我有一个GSP形式收集用户名,名字,姓氏,年龄和地址字段,并应保存到数据库中Person和Address基本上2表,只有一个地址。那么如何将代码写入映射2个域类的控制器(Person & Address)。
感谢您的回答。
UPDATE:我用下面的代码没有工作
package com.deltaintech.wr
class Person {
String username
String password
String firstname
String lastname
String email
Address address
static constraints = {
}
}
package com.deltaintech.wr
class Address {
String address1
String address2
String city
String state
String country
String zipcode
static constraints = {
}
}
package com.deltaintech.wr.register
import com.deltaintech.wr.*
class RegisterController {
def index = {
}
def register = {
Person person = new Person(params)
person.save()
}
}
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sample title</title>
</head>
<body>
<h1>Sample line</h1>
<g:form action="register">
User Name <g:textField name="username"/><br>
Password <g:passwordField name="password" /><br>
First Name <g:textField name="firstname"/><br>
Last Name <g:textField name="lastname"/><br>
Email <g:textField name="email" /><br>
Address1 <g:textField name="address.address1"/><br>
Address2 <g:textField name="address.address2" /><br>
City <g:textField name="address.city" /><br>
State<g:textField name="address.state" /><br>
Country <g:textField name="address.country" /><br>
Zip Code <g:textField name="address.zipcode" /><br>
<g:submitButton name="create" value="Create"/>
</g:form>
</body>
</html>
Error 500: Executing action [register] of controller [com.deltaintech.wr.register.RegisterController] caused exception: not-null property references a null or transient value: com.deltaintech.wr.Person.address; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com.deltaintech.wr.Person.address
Servlet: grails
URI: /system/grails/register/register.dispatch
Exception Message: not-null property references a null or transient value: com.deltaintech.wr.Person.address
Caused by: not-null property references a null or transient value: com.deltaintech.wr.Person.address
Class: RegisterController
At Line: [13]
我认为我忘记了一些东西。请尝试以下操作:将static belongsTo = [person:Person]添加到地址域类。在同一时间内保存两个域类所需的人员和地址之间建立了双向关系。如果你不想要这个,你可以在控制器类中执行以下操作:Address adr = new Address(params.address); Person person = new Person(params); person.address = adr.save(); – hitty5 2011-06-07 09:34:31