【问题标题】:Grails; how to refer to a domain property in native sql query圣杯;如何在本机 sql 查询中引用域属性
【发布时间】:2013-07-06 04:08:22
【问题描述】:

我有一个域类 UserProfile,它与另一个域类 User 具有一对一的关系。提供了域的结构。

сlass UserProfile {
String fio
String position
String phone
String email

static belongsTo = [user: User]

static constraints = {
          // some constraints
}
static mapping = {
   //some mapping; user property is not mapped
}    

我需要在 Grails 中为 UserProfile 域编写本机 sql 查询,但我不知道如何引用用户属性(静态 belongsTo = [user: User])。我试过 USER_ID 但它不起作用。 我不能直接使用映射部分命名列;我只需要找出 UserProfile 域中的用户列在数据库中是如何命名的,以及如何在本机 sql 查询中调用它。

【问题讨论】:

标签: sql grails mapping


【解决方案1】:

如果我有你的问题,非常简单,Grails gorm 在数据库中存储文件的约定是:

喜欢

    user_profile  for UserProfile -Domain

所有文件都用下划线分隔,大多数时候gorm在外键引用/或像上面的一对一和一对多这样的GORM关系之后添加_id

   [belongsTo=[user]] .

内部 SQL 表

    mysql describe user_profile ;

    ----------------------------------------------------------------
    User_Profile
    ----------------------------------------------------------------
    id
    version 
    foo           varchar(50)   
    postion
    email
    user_instance_id  int 
  -------------------------------------------------------------------

本地 SQL 查询将是:

   'select up.user_instance_id from user_profile as up '

通过查询用户表获取所有userInstance对象

   'select * from user where user.id = 'the id you get it from the above query'

我希望你对此有一些想法,如果我不明白,请告诉我。

【讨论】:

    【解决方案2】:

    我相信如果您在 UserProfile 中定义用户,那么您可以访问它并自动映射?它适用于我以前的项目,我希望它适用于此。

    сlass UserProfile {
    String fio
    String position
    String phone
    String email
    
    static belongsTo = [user: User]
    
    User userInstance;
    
    static constraints = {
              // some constraints
    }
    

    那你就可以用了

    UserProfile.executeQuery("select up.userInstance from UserProfile up")
    

    【讨论】:

    • 这不是原生 SQL。这就是 HQL。
    • 例子是HQL,但是在SQL中你仍然可以引用属性yes?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多