我没有收到任何错误,但我的应用没有在数据库中保存数据。
这里有profitTable.gsp
<g:form controller="dailyProfit" action="save" >
<div class="fieldcontain ${hasErrors(bean: dailyProfitInstance, field: 'date', 'error')} required>
<label for="date" >Date</label>
<g:datePicker name="date" precision="day" value="${dailyProfitInstance?.date}" />
</div>
<br>
<div class="fieldcontain ${hasErrors(bean: dailyProfitInstance, field: 'profit', 'error')} required>
<label for="profit">Profit</label>
<span class="required-indicator">*</span>
<g:field name="profit" value="${fieldValue(bean: dailyProfitInstance, field: 'profit')}" required=""/>
</div>
<br>
<g:submitButton name="create" class="save btn btn-default " value="${message(code: 'default.button.create.label', default: 'Create')}" />
</g:form>
这是我的控制器
package samplegrailsapp
class DailyProfitController {
def scaffold = DailyProfit
def index() {
render(view:"profitTable");
}
def save() {
// Date myDate = params.date('test', 'yyyy-MM-dd');
def dailyProfit = new DailyProfit(params)
params.date = params.date_year + "-0" + params.date_month + "-" + params.date_day
println params.toString();
dailyProfit.save()
render(view:"profitTable");
}
}
这是我的域类
package samplegrailsapp
import java.text.DateFormat
import java.text.SimpleDateFormat
import org.grails.databinding.BindingFormat
class DailyProfit {
@BindingFormat('yyyy-MM-dd')
Date date;
double profit;
static constraints = {
date (blank:false, nullable:false, validator: {value, object ->
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if(!(cal.getTime().before(value) || cal.getTime().equals(value))){
return false;
}
})
profit (blank:false, nullable:false, validator: {value, object ->
if (!value.toString().matches(/^([1-9]{1}[0-9]*\.{0,1}\d{0,2}|0\.[0-9]{1,2}|0)$/) ) return false;
})
}
static mapping = {
version false
//id generator:'assigned', name:'date'
id column: 'date', name: 'date', generator: 'assigned'
}
}
这是params内的数据。
[date_day:10, profit:8, date_year:2015, date_month:8, date:2015-08-10, create:Create, action:save, format:null, controller:dailyProfit]
当我查看日志时,这就是我得到的:
Hibernate:选择dailyprofi_.date,dailyprofi_.profit作为profit0_ 来自daily_profit dailyprofi_其中dailyprofi_.date =?休眠: 插入daily_profit(利润,日期)值(?,?)
为什么它不能从params中读取数据?我该怎么做才能解决它?
答案 0 :(得分:0)
代码的问题是dailyProfit.date采用日期对象,但您提供的是字符串日期。我也遇到了同样的问题。以下是代码:
def save() {
// Date myDate = params.date('test', 'yyyy-MM-dd');
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
def dailyProfit = new DailyProfit()
def updatedDate = params.date_year + "-0" + params.date_month + "-" + params.date_day
dailyProfit.date = sdf.parse(updatedDate);
dailyProfit.profit = params.profit
dailyProfit.save()
render(view:"profitTable");
}
请告诉我它是否有效。
快乐编码。