Grails里DOMAIN类的一对一,一对多,多对多关系总结及集成测试

终于干完这一章节,收获很多啊。

和DJANGO有类似,也有不同。

User.groovy:

package com.grailsinaction

class User {

    String loginId
    String password
    Date dateCreated

    static hasOne = [profile: Profile]
    static hasMany = [posts: Post, tags: Tag, following: User]
    static mapping = {posts sort: ‘dateCreated‘}

    static constraints = {
      loginId size: 3..20, unique: true, nullable: false
      password size: 6..8, nullable:false, validator: { passwd, user -> passwd != user.loginId }
      profile nullable: true
    }
}

Profile.groovy:

package com.grailsinaction

class Profile {
        User user
        byte[] photo
        String fullName
        String bio
        String homepage
        String email
        String timezone
        String country
        String jabberAddress

    static constraints = {
            fullName blank: false
            bio nullable: true, maxSize: 1000
            homepage url:true, nullable: true
            email email: true, blank: false
            photo nullable:true, maxSize: 2 * 1024 * 1024
            country nullable: true
            timezone nullable: true
            jabberAddress email: true, nullable: true
    }
}

Post.groovy:

package com.grailsinaction

class Post {
        String content
        Date dateCreated

    static constraints = {
            content blank: false
    }

        static belongsTo = [user: User]
        static hasMany = [tags: Tag]

        static mapping = { sort dateCreated: "desc"}
}

Tag.groovy:

package com.grailsinaction

class Tag {
        String name
        User user

    static constraints = {
            name blank: false
    }

        static hasMany = [posts: Post]
        static belongsTo = [User, Post]
}

UserIntegrationSpec.groovy:

package com.grailsinaction

import grails.test.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*

@Integration
@Rollback
class UserIntegrationSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    def "Saving our first user to the database"() {
            given: "A brand new user"
            def joe = new User(loginId: ‘Joe‘, password: ‘secret‘)
            when: "the user is saved"
            joe.save()

            then: "it saved successfully and can be found in the database"
            joe.errors.errorCount == 0
            joe.id != null
            User.get(joe.id).loginId == joe.loginId
        }

        def "Updating a saved user changes its properties"() {
            given: "An existing user"
            def existingUser = new User(loginId: ‘Joe‘, password: ‘secret‘)
            existingUser.save(failOnError: true)
            when: "A property is changed"
            def foundUser = User.get(existingUser.id)
            foundUser.password = ‘sesame‘
            foundUser.save(failOnError: true)

            then: "The change is reflected in the database"
            User.get(existingUser.id).password == ‘sesame‘
        }

        def "Deleting an existing user removes it from the database"() {
            given: "An existing user"
            def user = new User(loginId: ‘Joe‘, password: ‘secret‘)
            user.save(failOnError: true)

            when: "The user is deleted"
            def foundUser = User.get(user.id)
            foundUser.delete(flush: true)

            then: "The user is removed from the database"
            !User.exists(foundUser.id)
        }

        def "Saving a user with invalid properties causes an error"() {
            given: "A user which fails several field validations"
            def user = new User(loginId: ‘Joe‘, password: ‘tiny‘)
            when: "The user is validated"
            user.validate()

            then:
            user.hasErrors()

            "size.toosmall" == user.errors.getFieldError("password").code
            "tiny" == user.errors.getFieldError("password").rejectedValue
            !user.errors.getFieldError("loginId")
        }

        def "Recovering from a failed save by fixing invalid properties"() {
            given: "A user that has invalid properties"
            def chuck = new User(loginId: ‘chuck‘, password: ‘tiny‘)
            assert chuck.save() == null
            assert chuck.hasErrors()

            when: "We fix the invalid properties"
            chuck.password = "fistfist"
            chuck.validate()

            then: "The user saves and validates fine"
            !chuck.hasErrors()
            chuck.save()
        }

        def "Ensure a user can follow other users"() {
            given: "A set of baseline users"
            def joe = new User(loginId: ‘joe‘, password: ‘password‘).save()
            def jane = new User(loginId: ‘jane‘, password: ‘password‘).save()
            def jill = new User(loginId: ‘jill‘, password: ‘password‘).save()

            when: "Joe follows Jan & Jill, and Jill follows Jane"
            joe.addToFollowing(jane)
            joe.addToFollowing(jill)
            jill.addToFollowing(jane)

            then: "Follower counts should match follow people"
            2 == joe.following.size()
            1 == jill.following.size()
        }

}

PostIntegrationSpec.groovy:

package com.grailsinaction

import grails.test.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*

@Integration
@Rollback
class PostIntegrationSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    def "Adding posts to user links post to user"() {
            given: "A brand new user"
            def user = new User(loginId: ‘joe‘, password: ‘secret‘)
            user.save(failOnError: true)

            when: "Several posts are added to the user"
            user.addToPosts(new Post(content: "First post.....w002!"))
            user.addToPosts(new Post(content: "Second post......"))
            user.addToPosts(new Post(content: "Third post...."))

            then: "The user has a list of posts attached"
            3 == User.get(user.id).posts.size()
        }

        def "Ensure posts linked to a user can be retrieved"() {
            given: "A user with several posts"
            def user = new User(loginId: ‘joe‘, password: ‘secret‘)
            user.addToPosts(new Post(content: "First"))
            user.addToPosts(new Post(content: "Second"))
            user.addToPosts(new Post(content: "Third"))
            user.save(failOnError: true)

            when: "The user is retrieved by their id"
            def foundUser = User.get(user.id)
            def sortedPostContent = foundUser.posts.collect {
                it.content
            }.sort()

            then: "The posts appear on the retrieved user "
            sortedPostContent == [‘First‘, ‘Second‘, ‘Third‘]
        }

        def "Exercise tagging several post with various tags"() {
            given: "A user with a set of tags"
            def user = new User(loginId: ‘joe‘, password: ‘secret‘)
            def tagGroovy = new Tag(name:"groovy")
            def tagGrails = new Tag(name:"grails")
            user.addToTags(tagGroovy)
            user.addToTags(tagGrails)
            user.save(failOnError: true)

            when:"The user tags two fresh posts"
            def groovyPost = new Post(content: "A groovy post")
            user.addToPosts(groovyPost)
            groovyPost.addToTags(tagGroovy)

            def bothPost = new Post(content: "A groovy and grails post")
            user.addToPosts(bothPost)
            bothPost.addToTags(tagGroovy)
            bothPost.addToTags(tagGrails)

            then:
            user.tags*.name.sort() == [‘grails‘, ‘groovy‘]
            1 == groovyPost.tags.size()
            2 == bothPost.tags.size()

        }
}

时间: 2024-10-14 16:54:37

Grails里DOMAIN类的一对一,一对多,多对多关系总结及集成测试的相关文章

SQLAlchemy_定义(一对一/一对多/多对多)关系

目录 Basic Relationship Patterns One To Many One To One Many To Many Basic Relationship Patterns 基本关系模式 The imports used for each of the following sections is as follows: 下列的 import 语句,应用到接下来所有的代章节中: from sqlalchemy import Table, Column, Integer, Forei

mybatis 一对一 一对多 多对多

一对一 一对多 多对多 原文地址:https://www.cnblogs.com/cwone/p/11909271.html

PD 15.1 安装 破解 , 简单使用 (一对多,多对多关系生成sql脚本)

  1:运行  PowerDesigner15_Evaluation.exe 默认   2: 安装完毕后,不要执行,下面我们进行 破解 把 PowerDesigner15汉化+注册补丁  下的所有文件,覆盖 PD的安装目录下的文件 然后我们打开 PD,点击 帮助 –> About  看到下面窗口中红色方框,就表示已经破解 + 汉化成功 PD 15.1 安装 破解 , 简单使用 (一对多,多对多关系生成sql脚本)

表关系(一对一,一对多,多对多)

可以在数据库图表中的表之间创建关系,以显示一个表中的列与另一个表中的列是如何相链接的. 在一个关系型数据库中,利用关系可以避免多余的数据.例如,如果设计一个可以跟踪图书信息的数据库,您需要创建一个名为 titles 的表,它用来存储有关每本书的信息,例如书名.出版日期和出版社.您也可能保存有关出版社的信息,诸如出版社的电话.地址和邮政编码.如果您打算在 titles 表中保存所有这些信息,那么对于某出版社出版的每本书都会重复该出版社的电话号码. 更好的方法是将有关出版社的信息在单独的表,publ

django mysql 表的一对一 一对多 多对多

表结构的设计 一对一 多对一  将key写在多 多对多 外键: 描述  多对一的关系 写在多的一方 class Book(models.Model) title = models.CharField(max_length=32,unique=Ture) publisher = models.ForeignKey (to=Publisher,on_deleete=models.CASADE) publisher = models.ForeignKey(to='Publisher', on_dele

Hibernate 映射文件的配置 核心文件的配置 一对一 一对多 多对多 hibernate实现分页 Hibernate中session的关闭问题总结

以留言系统为实例 1 .配置映射文件:首先得引入约束dtd <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 然后<hibernate-mapping></hibernate-mapping>映射标签 <

EF里一对一、一对多、多对多关系的配置和级联删除

      参考 EF里一对一.一对多.多对多关系的配置和级联删除 EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

mybatis 一对一,一对多,多对多关系映射查询操作

定义两个类(对应数据库内两张表) User ,Account,每个Account属于一个User User类 及其 对应的IUserDao package com.itheima.domain; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Integer id; private Strin

Hibernate 集合映射 一对多多对一 inverse属性 + cascade级联属性 多对多 一对一 关系映射

1 . 集合映射 需求:购物商城,用户有多个地址. // javabean设计 // javabean设计 public class User { private int userId; private String userName; // 一个用户,对应的多个地址 private Set<String> address; private List<String> addressList = new ArrayList<String>(); //private Str