My domain layer looks like that:
#Resource(uri='/product')
class BasicProduct {
String title
String description
Double price
Date creationDate
Date changedDate
static constraints = {
//everything is by default NotNull
title(blank: false, unique: true)
description(blank: false)
price(blank: false, inList: [5,15,25,50,100])
creationDate(min: new Date())
}
}
My Bootstrap.groovy contains that code:
class BootStrap {
def init = { servletContext ->
new BasicProduct(title: "Product1", description:"blblblblbalablablalbalbablablablablblabalalbllba", price:5).save()
new BasicProduct(title: "Product2", description:"blblblblbalablablalbalbablablablablblabalalbllba", price:75).save()
new BasicProduct(title: "Product3", description:"blblblblbalablablalbalbablablablablblabalalbllba", price:50).save()
new BasicProduct(title: "Product4", description:"blblblblbalablablalbalbablablablablblabalalbllba", price:25).save()
new BasicProduct(title: "Product5", description:"blblblblbalablablalbalbablablablablblabalalbllba", price:15).save()
println "initializing data..."
}
However when I open the \product url I do not see any data.
Any ideas why?
I appreciate your answer!
For your dates you can do:
Date dateCreated
Date lastUpdated
static mapping = {
autoTimestamp true
}
Related
I'm trying to write additional properties to the log using {Properties} (which are not in the message template):
Used (FileSink) template:
"[{Level}] {Message}{NewLine}{Properties}{NewLine}{Exception}"
Log operation (simplified, normally the object array is given by a method parameter):
Log.Information("Start logging",
new object[]{
new { Version = "VersionString"},
new { StartDate = DateTime.Now },
new { Id = Guid.NewGuid() }
});
I also tired:
Log.Information("Start logging",
new object[]{
"VersionString",
DateTime.Now,
Guid.NewGuid()
});
I had a look on LogEventPropertyCapturingTests and this PR, but I couldn't get it working...
Update
I use wrapper functions like this:
public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
{
_MainLog.Information(messageTemplate, propertyValues);
}
if(show)
{
// Code to show a the event to the user
}
}
Update2 Found a way but it's not very nice, as the template-property-matching rudimentary.
public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
{
Regex matchProperties = new Regex("{[^}]+}");
int usedPropertiesCount = matchProperties.Matches(messageTemplate).Cast<Match>().Select(m => m.Value).Distinct().Count();
if (propertyValues.Length > usedPropertiesCount)
{
using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount)))
{
_MainLog.Information(messageTemplate, propertyValues);
}
}
else
{
_MainLog.Information(messageTemplate, propertyValues);
}
}
if(show)
{
// Code to show a the event to the user
}
}
The ForContext() method will do this:
Log.ForContext("Version", "VersionString")
.ForContext("Id", Guid.NewGuid())
.Information("Start logging");
(I've omitted StartDate because all Serilog events are already timestamped.)
This blog post series includes some posts on message templates plus context and correlation that cover this plus other alternatives.
I am developing one application in grails. I have following kind of mapping. Now I am saving object of DemoD class but its not saving values neither showing me any error while save. I have printed all created object and all looks fine. but still I am now able to save records.
class DemoS {
String firstName
String lastName
Long rollNumber
String address1
String address2
String city
String state
static constraints = {
address2 nullable:true
}
static hasMany = [demoAList: DemoA]
}
class DemoD {
Date date
static hasMany = [demoAList: DemoA]
def beforeInsert = {
date = new Date()
}
}
class DemoA {
Long id
Boolean absent
Boolean halfday
String notes
Date date
static belongsTo = [demoS:DemoS, demoD:DemoD]
static constraints = {
notes nullable: true
}
}
class UploadDataService {
def saveUploadedData(def dataList) {
def i = 0
DemoD ddObj = new DemoD()
//Getting this dataList from excel and now creating object for each row.
dataList?.each{ rowList ->
if(i != 0){
def dsObj = DemoS.get(rowList[0]?.longValue())
DemoA daObj = new DemoA([id:rowList[0]?.longValue(),absent:rowList[1],halfday:rowList[2],notes:rowList[3] ? rowList[3] : ''])
dsObj.addToDemoAList(daObj)
daObj.demoS = dsObj
ddObj.addToDemoAList(daObj)
daObj.demoD = ddObj
}
i++
}
ddObj.save(saveOnError: true)
}
}
I'm loading data into my model from BootStrap.groovy but I can't figure out why only the first set of 4(ListItPlan) are the only ones getting loaded to the database(hql). When I look at the tables using dbconsole, the other two tables are empty (Plan,Cred). Does it have something to do with the order in which the data is loaded or maybe constraints (which I only have on the ListItPlan model)?
class BootStrap {
def init = { servletContext ->
new ListItPlan(m_id: "248656", plan_id: "12345XX9876543").save()
new ListItPlan(m_id: "209459", plan_id: "12345XX9876543").save()
new ListItPlan(m_id: "248656", plan_id: "56748XXX123933").save()
new ListItPlan(m_id: "209459", plan_id: "56748XXX123933").save()
new Plan(plan_id: "12345XX9876543", p_id_type: "PLAN-ID").save()
new Plan(plan_id: "56748XXX123933", p_id_type: "PLAN-ID").save()
new Cred(m_id: "248656", d_name: "Lorem Ipsum").save()
new Cred(m_id: "209459", d_name: "Ipsum").save()
}
def destroy = {
}
}
fyi: I don't see any errors in the console.
So, now I'm having trouble with the pk constraint. After doing some reading, I know the belongsTo and hasMany is the culprit, but I cannot seem to get the order correct when adding the data. Do I create the Cred first and then put it in the ListItPlan? Like this...
def d1 = new Cred(m_id: "248656", d_name: "Lorem Ipsum").save(failOnError: true)
def ldp1 = new ListItPlan(Cred : d1, plan_id: "12345XX9876543").save(failOnError: true)
Here's my model...
…
class ListItPlan {
String m_id
String plan_id
String toString() {
"${plan_id}"
}
static hasMany = [creds : Cred, plans : Plan]
static constraints = {
m_id()
plan_id()
}
}
…
class Cred {
String m_id
String g_name
static belongsTo = [owner : ListItPlan]
static hasMany = [plans : Plan]
static constraints = {
}
}
…
class Plan {
String plan_id
String plan_id_type
static belongsTo = [listItPlan : ListItPlan, cred: Cred]
static constraints = {
}
}
I'm writing an application on Grails. I'm trying to add child database record to parent table using addTo-method. I follow this documentation about addTo-method. And for example, documentation says create parent-class:
class Author { String name
static hasMany = [fiction: Book, nonFiction: Book]
}
Follow this I created my parent-class:
class Cafee {
String cafeeName = ""
int totalReservationPlaces = 0
double placeCost = 0
String currencyType = ""
boolean isReservationAvailable = false
boolean reservationTimeLimit = false
boolean reservationDateLimit = false
int totalPlaces = 0
long startTimeLimit = 0
long endTimeLimit = 0
Date startDateLimit = new Date()
Date endDateLimit = new Date()
static constraints = {
cafeeName blank: false, unique: true
}
String getCafeeName(){
return cafeeName
}
static hasMany = [admin: Person]
}
Documentation says create child-class:
class Book { String title
static belongsTo = [author: Author]
}
Follow this I've created my child-class:
class Person {
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
String firstName
String lastName
String email
String inn = ""
boolean isAdminCafee = false
static transients = ['springSecurityService']
static belongsTo = [cafee:Cafee]
static constraints = {
username blank: false, unique: true
firstName blank: false
lastName blank: false
password blank: false
email blank: false, unique: true
}
static mapping = {
password column: '`password`'
}
Set<Authority> getAuthorities() {
PersonAuthority.findAllByPerson(this).collect { it.authority }
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
}
And documentation says to add child record to parent I must do something this:
def fictBook = new Book(title: "IT")
def nonFictBook = new Book(title: "On Writing: A Memoir of the Craft")
def a = new Author(name: "Stephen King")
.addToFiction(fictBook)
.addToNonFiction(nonFictBook)
.save()
Follow it in Bootstrap I've done this:
def user = Person.findOrSaveWhere(username: 'testerAndrewRes', password:'password', firstName:'Andrew', lastName:'Bobkov', email:'pragm#gmail.com', isAdminCafee: true,
inn: '1234567890')
println user
if(!user.authorities.contains(adminRole))
{
PersonAuthority.create(user, adminRole, true)
}
def newCafe = new Cafee(cafeeName: "Tarelka").addToAdmin(user).save()
But I get an error:
ERROR context.GrailsContextLoaderListener - Error initializing the application: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person
Message: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: restorator.auth.Person
What I do wrong?
The error message is clear I think.
Try adding:
user.save(flush:true)
before:
def newCafe = new Cafee(cafeeName: "Tarelka").addToAdmin(user).save()
I am new to groovy/grails, and I'm trying to to do a criteria search that finds all posts for a month, basically like this:
def getUserMinutesForYear(User user, Date date){
Date firstDate = new GregorianCalendar(date.year, Calendar.JANUARY, 1, 0, 0, 0).time
Date lastDate = new GregorianCalendar(date.year, Calendar.DECEMBER, 31, 23, 59, 59).time
def c = JobRegistration.createCriteria()
def minutes = c.get {
and{
eq("user.id", user.id)
between("job.happening", firstDate, lastDate)
}
projections {
sum("minutesWorked")
}
}
return minutes
}
The domain classes are
class Job {
String title
String description
Date happening
static hasMany = [registrations:JobRegistration]
}
class User {
static hasMany = [authorities: Role, registrations: JobRegistration]
static belongsTo = Role
String username
}
class JobRegistration {
Job job
User user
Integer minutesWorked
static belongsTo = [user:User,job:Job]
static constraints = {
user(blank: false)
job(blank:false)
minutesWorked(nullable :true)
}
String toString(){
return user.userRealName
}
}
Now, why do I get this exception?
org.codehaus.groovy.runtime.InvokerInvocationException: org.hibernate.QueryException: could not resolve property: job.happening of: JobRegistration
You need to nest the job relationship (you can also just us eq with user):
def minutes = c.get {
and{
eq("user", user)
job{
between("happening", firstDate, lastDate)
}
}
projections {
sum("minutesWorked")
}
}
cheers
Lee