hasmany belongsTo,namedQuery belongsTo和hasmany instantiation grails domain之间的区别

时间:2014-02-15 19:23:25

标签: grails gorm grails-domain-class

在grails中,我有两个域类Question和QuestionOption.One问题有很多选项。每个选项都有一个问题。 我经历了4种不同的场景。 这些场景结合了instantiation-namedQuery,belongsTo-namedQuery,instantiation-hasMany和belongsTo-hasMany。

Scenario 1:

class Question
{
  String quesText
  static constraints={}
  static namedQueries={
    getAllQuestionOptions{question->
      return QuestionOption.findAllWhere(question:question)
    }
  }
}

class QuestionOption
{
  String optionText
  Question question
  static constraints={}
}

Scenario 2:
class Question
{
  String quesText
  static constraints={}
  static namedQueries={
    getAllQuestionOptions{question->
      return QuestionOption.findAllWhere(question:question)
    }
  }
}

class QuestionOption
{
  String optionText
  static constraints={}
  static belongsTo=[question:Question]
}

Scenario 3:
class Question
{
  String quesText
  static constraints={}
  static hasMany=[questionOption:QuestionOption] 
}

class QuestionOption
{
  String optionText
  Question question
  static constraints={}
}

Scenario 4:
class Question
{
  String quesText
  static constraints={}
  static hasMany=[questionOption:QuestionOption] 
}

class QuestionOption
{
  String optionText
  static constraints={}
  static belongsTo=[question:Question]
}

我在mysql中使用了所有这些场景,所有场景都使用了相同的架构

mysql> desc question;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version     | bigint(20)   | NO   |     | NULL    |                |
| ques_text   | varchar(255) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc question_option;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version     | bigint(20)   | NO   |     | NULL    |                |
| option_text | varchar(255) | NO   |     | NULL    |                |
| question_id | bigint(20)   | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

在级联,单向双向和聚合组合方面使用这些方案有什么区别? 双向意味着当两个实体彼此了解时。单向意味着第一个实体知道第二个但反向不是真的。 为了理解级联,我提到了这一点:http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/。 请帮忙

1 个答案:

答案 0 :(得分:0)

Grails中的

belongsTohasMany关联会在更新/删除实例时影响cascading行为。它对命名查询或查询一般没有影响。