2016-12-05 7 views
1

У меня есть домен, как это ...получить родительские данные в список массива

class Invoice { 

    String invoiceNo 
    Date invoiceDate 
    Date dueDate 
    BigDecimal totalAmount 

    Date sendDate 
    Customer customer 
    String fromSOorDO   

    static mapping = { 
     //formula to calculate dueDate (invoiceDate + tempo) 
     dueDate formula:"ADDDATE(invoice_date, tempo)" 
    } 

    static constraints = {   
    } 

} 

мне нужно передать все данные из домена invoice к Array List с parent «s имя, а не id.

Например, из области invoice, мы можем видеть Customer customer.

Когда мы видим из базы данных, поле customer является id как 1, 2, 3 где принадлежит таблице Customer.

Это - область обслуживания клиентов.

class Customer { 
    String code 
    String name 
    String address 
    String phoneNo 

    static constraints = {} 
} 

И мне нужно передать всю фактуру данных в ArrayList, где Customer «ы id заменен Customer» ы name ..

Пример данные:

Таблица invoice имеет ряд с customer = 1

После этого стол клиент, как это:

id | code | name | address| phoneNo| 
1 | A |aaaaaa| Street |123132 | 
2 | B |bbbbbb| Street |454545 | 

При получении домена invoice с полем customer в качестве имени Клиента и заполнения его в hashMap.

def invoice = c.list(params) { 
    ge("invoiceDate", dateFrom) 
    eq("deleteFlag", "N") 
    eq("cif", cif) 
} 

def map = new HashMap() 
map.put("invoiceList",invoice) 

я пытался использовать collect как это и получаю эту ошибку:

def c = Invoice.createCriteria() 
    def invoice = c.list(params) { 
     ge("invoiceDate", dateFrom) 
     eq("deleteFlag", "N") 
     eq("cif", cif) 
    }.collect{ invoice -> 
     invoice.properties.collect{ it } + [customer:invoice.customer.name] 
    } 



ERROR org.grails.web.errors.GrailsExceptionResolver - IllegalStateException occurred when processing request: [POST] /api/listofinvoice/index - parameters: 
lastupdate: 01/01/2016 
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional one here. Stacktrace follows: 
java.lang.IllegalStateException: No Datastore Session bound to thread, and configuration does not allow creation of non-transactional one here 
     at grails.beans.util.LazyMetaPropertyMap.entrySet(LazyMetaPropertyMap.java:224) ~[grails-core-3.1.1.jar:3.1.1] 
     at com.vastpalaso.market.InvoiceController$_closure14$_closure23$$EQ4ZWTHZ.doCall(InvoiceController.groovy:607) ~[na:na] 
     at com.vastpalaso.market.InvoiceController$_closure14$$EQ4ZWTHV.doCall(InvoiceController.groovy:602) ~[na:na] 
     at grails.plugin.springsecurity.web.UpdateRequestContextHolderExceptionTranslationFilter.doFilter(UpdateRequestContextHolderExceptionTranslationFilter.groovy:64) ~[spring-security-core-3.1.1.jar:na] 
     at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.groovy:53) ~[spring-security-core-3.1.1.jar:na] 
     at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62) ~[spring-security-core-3.1.1.jar:na] 
     at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58) ~[spring-security-core-3.1.1.jar:na] 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_111] 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_111] 
     at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111] 
+0

сделать вас действительно ли нам нужно видеть ВСЕ свойства вашего домена? в том числе, прокомментировал какой-то mumbo-jumbo? – injecteer

+0

@ injecteer done – akiong

ответ

1

У вас есть 2 варианта здесь:

1) собирать имена клиентов в коде:

def invoice = c.list(params) { 
    ge("invoiceDate", dateFrom) 
    eq("deleteFlag", "N") 
    eq("cif", cif) 
}.collect{ invoice -> invoice.properties.collect{ it } + [ customer:invoice.customer.name ] } 

2) Использовать projection:

def invoice = c.list(params) { 
    projections { 
     property 'invoiceNo' 
     property 'invoiceDate' 
     // other properties 
     customer { 
      property 'name' 
     } 
    } 
    ge("invoiceDate", dateFrom) 
    eq("deleteFlag", "N") 
    eq("cif", cif) 
} 

Обратите внимание, что в обоих случаях вы получите список Map сек случаях вместо ваших Invoce объектов

+0

да, этот ... мне нравится, спасибо .. – akiong

+0

если я хочу пройти больше, не только клиент, то вот так? '.collect {invoice -> invoice.properties.collect {it} + [клиент: invoice.customer.name, customer2: invoice.customer2.name]} ' – akiong

+0

Я попытался использовать ваше решение с помощью' collect', см. мой обновленный вопрос – akiong

1

попробовать, как это ..

def c = Invoice.createCriteria() 
    def invoice = c.list(params) { 
     createAlias('customer','customer') 
     projections { 
      property ('invoiceNo','invoiceNo') 
      property ('invoiceDate','invoiceDate') 
      property ('dueDate','dueDate') 
      property ('totalAmount','totalAmount') 
      property ('sendDate','sendDate') 
      property ('customer.name','customer.name') 

     } 

     ge("invoiceDate", dateFrom) 
     eq("deleteFlag", "N") 
     eq("cif", ciff) 
    } 

увидеть это: Question

+0

ты мой герой: D – akiong