【问题标题】:Retrieving value from database in Grails在 Grails 中从数据库中检索值
【发布时间】:2016-09-16 18:28:40
【问题描述】:

我的数据库中有一个名为 invoice_number 的列。

class Customer {
    String name  
    int invoiceNumber

    static constraints = {
        name(blank: false)
        invoiceNumber(unique: true)
    }
}

index.gsp 文件中没有 invoice_number 字段。

<g:form controller="customer">
    Name:<br>
    <g:textField name="name"></g:textField><br> 
    <g:actionSubmit value="Submit" action="Save"></g:actionSubmit><br>
</g:form>

我想生成一个发票号,并增加一个差5。例如,第一个客户提交表单时,发票号可能生成为105。第二个客户提交表单时,发票号应该是110 . 它们应该保存在数据库中并且它们必须是唯一的。 然后,我想从数据库中为提交表单的客户检索发票编号,然后将该发票编号传递给另一个 gsp 文件。

我该怎么做?

【问题讨论】:

  • 嗯...所以一个客户只能有一张发票?曾经?将发票编号增加 5 是否有真正的商业原因? 106..109 会发生什么?
  • 正如@railsdog 所指出的,为什么要将发票编号增加5?您可以简单地将其增加1,它仍然可以是唯一的,对吧?同样从您的域类来看,似乎只会为客户映射一张发票。这是业务逻辑吗?
  • 这里的一切似乎都错了。这就是为什么您没有收到任何好的答案。正如 railsdog 所提到的 - 1 个用户和 1 个发票似乎很奇怪。您应该将发票创建为一个类并向用户添加一对多(如果您想要超过 1 个发票)。并且该数字可以是域函数afterInsert,即invoiceNumber = id*5 +100 或类似的东西。 (但仅当您将发票作为单独的类时才有效。
  • 谢谢。请查看我的回答并解释我的疑问

标签: grails


【解决方案1】:

您需要在controller's action 中添加生成/递增 invoiceNumber 的逻辑,您正在调用form submit

【讨论】:

    【解决方案2】:

    可能会让您开始上路(但我仍然没有收到每个客户零件的 1 张发票,或者以 5 为增量)。

    是的,正如 Abhinandan 所说,您可以将 ID 创建逻辑放在控制器中,但更可重用的路线可能是创建自定义键生成器,并让您的类使用此生成器来生成记录 ID。

    假设我们有:

    package tester2
    class Custo {
        String id  // string just to show it can be anything
        String name  
    
        // tell GORM about your id attribute, and setup your 'id' column
        // to use a custom id generator function
        static mapping = {
            id column:"id", generator:"tester2.CustomIdGenerator"
        }
    }
    

    然后在 src/groovy/tester2/CustomIdGenerator.groovy 中

    package tester2
    import org.hibernate.id.IdentifierGenerator
    import org.hibernate.engine.spi.SessionImplementor
    
    class CustomIdGenerator implements IdentifierGenerator {
        public synchronized Serializable generate(SessionImplementor session, Object obj) {
            // here's where you would have to access some persistent store to
            // remember your last generated ID, fetch the last value, add 5,
            // and store that new value to be ready for the next call 
            // -- don't know what DBMS you intend to use, but some have
            // sequence support that will let you tinker with the starting
            // point and increment. Maybe it's a simple as setting up a
            // customized sequence and asking for nextVal()
            // 
            // for this example, I just use a random UUID
            return UUID.randomUUID().toString()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多