Japanese DomainClass Dynamic Methods...

Last updated by admin 4 years ago

???????? ?????????????????? Domain Class Dynamic Methods & Properties

?????? Properties

errors

?? Description

A list of errors from the last call to the "validate" or "save" method ?????????? "validate" ? "save" ??????????????????

{color:black}Example{color}

def b = new Book(title:"The Shining")
if(!b.validate()) {
    b.errors.each {
          println it
    }
}

constraints

?? Description

A list of org.codehaus.groovy.grails.validation.ConstrainedProperty instances applied against the domain class by the constraints property (see Validation) ??????????? constraints ????????????????org.codehaus.groovy.grails.validation.ConstrainedProperty ????????? (??????????)

{color:black}? Example{color}

def b = new Book(title:"The Shining")
b.constraints.each {
      println it.name
      println it.maxLength
}

properties

?? Description

Allows access to the domain class properties as a map and perform types conversion when set allowing properties to be set from request parameters for {color:black}example{color}. Map????????????????????????????????????????????????????????????????

{color:black}? Example{color}

def b = new Book(title:"The Shining")
b.properties = this.params

???? Methods

add

Description 

Adds a domain class relationship to a specific one-to-many or many-to-many relationship.

Parameters 
  • to -  specifies the hasMany relationship name to which the object is being added
Example

def a = new Author(name:"Stephen King")
             .add(to:"fiction",
                   new Book(title:"IT"))
             .add(to:"non-fiction",
                   new Book(title:"On Writing: A Memoir of the Craft"))
             .save()

add*

Description 

Adds a domain class relationship for one-to-many or many-to-many relationship, where the relationship is indicated by the class used as the suffix to the method.

Example

def a = new Author(name:"Stephen King")
             .addBook(new Book(title:"IT"))
             .addBook(new Book(title:"The Stand"))
             .save()

delete

?? Description

Deletes a domain class instance from the database ????????????????????????????

{color:black}? Example{color}

def b = Book.get(1)
b.delete()

discard

?? Description

Discards any changes that have been made during an update. Note that this method will not clean or reset the object with the original values it will just prevent it from being automatically saved by Grails. ????????????????????????????????????????????????????????Grails?????DB?????????????

{color:black}? Example{color}

def b = Book.get(1)
b.title = "Blah"
b.discard() // ???????????????changes won't be applied now

hasErrors

?? Description

True if the domain class instance has errors following a call to "validate" or "save" "validate" ?? "save" ????????????????????????True??????

{color:black}? Example{color}

def b = new Book(title:"The Shining")
b.validate()
if(b.hasErrors()) {
    b.errors.each {
          println it
    }
}

ident

?? Description

Returns the value of the identity property of the domain class regardless of the name of the identity property itself ?????????????????????????????????????????

{color:black}? Example{color}

def b = new Book(title:"The Shining")
b.save()

println b.ident()

merge

Description

see Hibernate3's merge

refresh

?? Description

Refreshes a domain classes state from the database ?????????????????????????

{color:black}? Example{color}

def b = Book.get(1)
b.refresh()

save

?? Description

Saves a domain class instance to the database cascading updates to any child instances if required. Returns false if validation failed and the instance was not saved ????????????????????????????????????????????????????????????????????????????????????????? false??????

Parameters
  • validate (optional) - ????????????????false??? Set to false if validation should be skipped
{color:black}? Example{color}

def b = new Book(title:"The Shining")
if( !b.save() ) {
   b.errors.each {
        println it
   }
}

validate

?? Description

Validates a domain class against the applied constraints (see Validation) ?????constraints????????????? (??????????)

{color:black}? Example{color}

def b = new Book(title:"The Shining")
if( !b.validate() ) {
   b.errors.each {
        println it
   }
}

??????????? Static Methods

count

?? Description

Counts the number of instances in the database and returns the result ???????????????????????????

????? Parameters

None

{color:black}? Example{color}

def noOfBooks = Book.count()

countBy

?? Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that count the number of records returned Grails???????????????????????????????????????????

? Examples

class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
def c = Book.countByTitle("The Shining")
c = Book.countByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
c = Book.countByReleaseDateBetween(firstDate, new Date())
c = Book.countByReleaseDateGreaterThanOrEqual(firstDate)
c = Book.countByTitleLike("%Hobbit%")
c = Book.countByTitleNotEqual("Harry Potter")
c = Book.countByReleaseDateIsNull()
c = Book.countByReleaseDateIsNotNull()

createCriteria

?? Description

Creates a grails.orm.HibernateCriteriaBuilder instance for the domain class. (see Builders) ????????grails.orm.HibernateCriteriaBuilder????????? (???????)

{color:black}? Example{color}

def c = Account.createCriteria()
def results = c {
	like("holderFirstName", "Fred%")
	and {
              between("balance", 500, 1000)
              eq("branch", "London")
	}
	maxResults(10)
	order("holderLastName", "desc")
}

exists

?? Description

Checks whether an instance exists for the specified id and returns true if it does ?????id????????????????????????true????

????? Parameters
  • id (??) - ???????id The id of the instance
{color:black}? Example{color}

if(Account.exists(1)) {
     // do something
}

executeQuery

?? Description

Allows the execution of HQL queries against a domain class HQL ????????????????????????

????? Parameters
  • query (??) - HQL????? A query in HQL
  • params (??) - ???????????????????????????????? A set of positional parameters as a List of or single object
{color:black}? Example{color}

Account.executeQuery( "select distinct a.number from Account a where a.branch = ?", 'London' );
Account.executeQuery( "select distinct a.number from Account a where a.branch = ? and a.created > ?", ['London',lastMonth] );

find

?? Description

Finds and returns the first result for the given query or null if no instance was found ????????????????????????????????????null??????

????? Parameters
  • query (??) - HQL?????????????????????????Either an HQL query or a instance of the domain class for query by {color:black}example{color}
  • arguments (??) - ????????????HQL?????????? A List of arguments for a positional parametrized HQL query
{color:black}? Example{color}

Book.find("from Book as b where b.author='Dan Brown'") // Dan brown's first book
Book.find("from Book as b where b.author=?",['Dan Brown']) // with a positional parameter

def b = new Book(author:"Dan Brown") Book.find(b) // query by example

findAll

?? Description

Finds all of the domain class instances for the specified query ??????????????????????????????????

????? Parameters
  • query (??) - HQL????????????????????????? Either an HQL query or a instance of the domain class for query by {color:black}example{color}
  • arguments (??) - ????????????HQL?????????? A List of arguments for a positional parametrized HQL query
  • max (??) - ?????????? The maximum number of results to retrieve
? Examples

Book.findAll() // ?? everything
Book.findAll("from Book as b where b.author='Dan Brown'",10) // Dan Brown????10? The first 10 books from Dan Brown
Book.findAll("from Book as b where b.author=?",['Dan Brown'],10) // ?????????????? with a positional parameter

def b = new Book(author:"Dan Brown") Book.findAll(b) // query by example

findBy

?? Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return the first result of the query Grails?????????????????????????????????????????????????

? Examples

class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
def b = Book.findByTitle("The Shining")
b = Book.findByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
b = Book.findByReleaseDateBetween(firstDate, new Date())
b = Book.findByReleaseDateGreaterThanOrEqual(firstDate)
b = Book.findByTitleLike("%Hobbit%")
b = Book.findByTitleNotEqual("Harry Potter")
b = Book.findByReleaseDateIsNull()
b = Book.findByReleaseDateIsNotNull()

findAllBy

?? Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return all instances of the domain class Grails?????????????????????????????????????????????????

? Examples

class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
def results = Book.findAllByTitle("The Shining", [max:10, sort:"title", order:"desc", offset:100] )
results = Book.findAllByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
results = Book.findAllByReleaseDateBetween(firstDate, new Date())
results = Book.findAllByReleaseDateGreaterThanOrEqual(firstDate)
results = Book.findAllByTitleLike("%Hobbit%")
results = Book.findAllByTitleNotEqual("Harry Potter")
results = Book.findAllByReleaseDateIsNull()
results = Book.findAllByReleaseDateIsNotNull()

findWhere

?? Description

Uses named arguments that match the property names of the domain class to produce a query that returns the first result. ??????????????????????????????????????????????????

? Examples

class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
def b = Book.findWhere(title:"The Shining", author:"Stephen King")

get

?? Description

Retrieves an instance of the domain class for the specified id, otherwise returns null ?????id?????????????????????????????null??????

? Examples

def b = Book.get(1)

list

?? Description

Lists all of the instances of the domain class. ?????????????????????????

????? Parameters
  • max - ??????? The maximum number to list
  • offset - ????????????? The offset from the first result to list from
  • order - "desc" ?? "asc" ??????? The order to list by, either "desc" or "asc"
  • sort - ???????????? The property name to sort by
? Examples

def results = Book.list() // ?? everything
def results = Book.list(max:10) // ??10? 10 results
def results = Book.list(max:10, offset:100) // ?????100 ?10? 10 results, offset by 100
def results = Book.list(max:10, offset:100, sort:"title", order:"desc") // ?????100 ?10? title?????????
?  10 results, offset by 100, orderd by title in descending order

listOrderBy

?? Description

Lists all of the instances of the domain class ordered by the property in the method expression ????????????????????????????????????????

????? Parameters
  • max - ??????? The maximum number to list
? Examples

def results = Book.listOrderByAuthor() // ?? everything
def results = Book.listOrderByTitle(max:10) // ??10? 10 results
def results = Book.listOrderByTitle(max:10, offset:100, order:"desc") // 10???????100??  10 results, offset from 100

withCriteria

Description

Allows inline execution of criteria with a closure. (Since 0.4)

Parameters
  • arguments (optional) - A map on named arguments that will be set on the criteria instance
  • closure - A closure that defines the criteria
Examples

def results = Book.withCriteria {
    def now = new Date()
    between('releaseDate', now-7, now)
    like('title', '%Groovy%')
}

withTransaction

Description

Uses Spring's TransactionTemplate combination with a closure. Since 0.4

Parameters
  • closure - A closure that gets passed an instance of the Spring TransactionStatus to allow programmatic management of savepoints (See SavepointManager) and transaction rollback
Examples

Book.withTransaction { tx ->
    def b = new Book(title:"Groovy in Action")

b.save()

// some logic that goes wrong tx.setRollbackOnly()

}