grails create-domain-class es.ua.expertojava.todo.todo
package es.ua.expertojava.todo
class Todo {
String title
String description
Date date
Date reminderDate
String url
Boolean done = false
Category category
static hasMany = [tags:Tag]
static belongsTo = [Tag]
static constraints = {
title(blank:false)
description(blank:true, nullable:true, maxSize:1000)
date(nullable:false)
reminderDate(nullable:true)
url(nullable:true, url:true)
done(nullable:false)
category(nullable:true)
}
String toString(){
title
}
}
class Book{
}
class ActiveOperation{
....
Book book
....
}
Relación unidireccional desde las operaciones activas hacia los libros
class Book{
....
ActiveOperation actoper
....
}
class ActiveOperation{
....
static belongsTo = [book:Book]
....
}
Inserciones y borrados en cascada.
class Book{
....
static hasOne = [actoper:ActiveOperation]
static constraints = {
actoper unique:true
}
....
}
class ActiveOperation{
....
Book book
....
}
Relación bidireccional entre libros y operaciones activas y columna book_id en la tabla active_operation
class Category {
....
static hasMany = [todos:Todo]
....
}
class Todo {
....
Category category
....
}
Inserciones y actualizaciones en cascada
class Category {
....
static hasMany = [todos:Todo]
....
}
class Todo {
....
static belongsTo = [category:Category]
....
}
Borrados en cascada
//Ejemplo para insertar datos en relaciones
def todo = new Todo(title:"Limpiar cocina", description:"Limpiar la cocina a fondo", ...)
def category = new Category(name:"Hogar")
category.addToTodos(todo)
category.save()
//Ejemplo para eliminar datos de relaciones
category.removeFromTodos(todo)
category.save()
//Ejemplo para buscar tareas dentro de una categoría
def todosfound = category.todos.find {it.title = "Limpiar cocina"}
class Tag{
....
static hasMany = [todos:Todo]
....
}
class Todo{
....
static hasMany = [tags:Tag]
static belongsTo = Tag
....
}
package es.ua.expertojava.todo
class Todo {
String title
String description
Date date
Date reminderDate
String url
Boolean done = false
Category category
static hasMany = [tags:Tag]
static belongsTo = [Tag]
static constraints = {
title(blank:false)
description(blank:true, nullable:true, maxSize:1000)
date(nullable:false)
reminderDate(nullable:true)
url(nullable:true, url:true)
done(nullable:false)
category(nullable:true)
}
String toString(){
title
}
}
date(nullable:true,
validator: {
if (it) {
return it?.after(new Date())
}
return true
}
)
reminderDate(nullable:true,
validator: { val, obj ->
if (val && obj.date) {
return val.before(obj?.date)
}
return true
}
)
grails.gorm.default.constraints = {
max20chars(nullable: false, blank: false, maxSize:20)
}
class User {
...
static constraints = {
password shared: "max20chars"
}
}
static mapping = {
//Todo el mapeado de la tabla aquí
}
class Todo {
....
static mapping = {
table 'tbl_todo'
description column:'desc'
}
}
class Todo {
....
static mapping = {
version false
}
}
class Person {
String firstName Pet pet
static hasMany = [addresses: Address]
static mapping = {
addresses lazy: false
pet fetch: 'join'
}
}
class Address {
String street
String postCode
}
class Pet {
String name
}
grails-app/conf/DataSource.groovy
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
singleSession = true
flush.mode = 'manual'
}
class User {
...
static mapping = {
table 'tbl_users'
cache usage: 'read-only', include: 'non-lazy'
}
}
class Person {
String firstName
static hasMany = [addresses: Address]
static mapping = {
table 'people'
version false
addresses column: 'Address', cache: true
}
}
static mapping = {
id composite: ['title', 'category']
}
class User{
....
}
class Administrator extends User{
....
}
class Registered extends User{
....
}
class Guest extends User{
....
}
class User{
....
}
class Administrator extends User{
static mapping = {
table = 'administrator'
}
}
class Registered extends User{
static mapping = {
table = 'registered'
}
}
class Guest extends User{
static mapping = {
table = 'guest'
}
}
class User{
.....
static mapping = {
tablePerHierarchy false
}
}
class User {
static transients = ["confirmPassword"]
String username
String password
String confirmPassword
String name
String surnames
}
class Todo {
....
User createdBy
User lastModifiedBy
def beforeInsert = {
createdBy = session?.user
lastModifiedBy = session?.user
}
def beforeUpdate = {
lastModifiedBy = session?.user
}
}
class Todo {
....
Date dateCreated
Date lastUpdated
}
Si queremos desactivar esta característica
static mapping = {
autoTimestamp false
}
Todo.findAllByTitleAndDescriptionAndDone('Pintar cocina',null,false)
def sentenciaHQL1 = Todo.find("From Todo as t")
def hqlsentence2 = Todo.findAll("from Todo as t where t.title='Pintar cocina'")
def hqlsentence3 = Todo.findAll("from Todo as t where t.title=?", ["Escribir tests unitarios"])
def hqlsentence4 = Todo.findAll("from Todo as t where t.title=:title", [title:"Cocinar pastel"])
Todo.executeQuery("select date from Todo t where t.title='Pintar cocina'")
void nextTodos() {
def c = Todo.createCriteria()
def result = c{
between("date",new Date(),new Date()+10)
maxResults(15)
order("date","asc")
}
}
and {
between("date", new Date()-10, new Date())
ilike("content", "%texto%")
}
or {
between("date", new Date()-10, new Date())
ilike("content", "%texto%")
}
not {
between("date", new Date()-10, new Date())
ilike("content", "%texto%")
}
grails create-service es.ua.expertojava.todo.todo
package es.ua.expertojava.todo
import grails.transaction.Transactional
@Transactional
class TodoService {
def serviceMethod() {
}
}
import grails.transaction.Transactional
class BookService {
@Transactional(readOnly = true)
def listBooks() {
Book.list()
}
@Transactional
def updateBook() {
// ...
}
def deleteBook() {
// ...
}
}
package es.ua.expertojava.todo
import grails.transaction.Transactional
class TodoService {
def getNextTodos(Integer days, params) {
Date now = new Date(System.currentTimeMillis())
Date to = now + days
Todo.findAllByDateBetween(now, to, params)
}
def countNextTodos(Integer days) {
Date now = new Date(System.currentTimeMillis())
Date to = now + days
Todo.countByDateBetween(now, to)
}
}
class TodoController {
def todoService
....
def listNextTodos(Integer days) {
respond todoService.getNextTodos(days, params),
model:[todoInstanceCount: todoService.countNextTodos(days)],
view:"index"
}
....
}
curl -v -H "Accept: text/xml" -H "Content-type: text/xml" -X GET http://localhost:8080/todo/todo/listNextTodos?days=2
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X GET http://localhost:8080/todo/todo/listNextTodos?days=2
class TodoService{
static scope = 'session'
...
}
Sólo necesitaríamos una url para gestionar nuestra entidad. http://localhost:8080/todo/todo/id_todo