grails一對多雙向關聯

來源:互聯網
上載者:User

標籤:blog   http   io   os   ar   使用   java   資料   div   

前面分享了一些學習grails的心得,可是grails的知識還遠不止這些,這次整理了一點有關grails一對多雙向關聯關係的知識。我認為這樣的關聯用的地方太多了,這次準備的範例是城市和地區的相關範例。

1.領域模型

class CityInfo {    static hasMany = [area:AreaInfo]    static fetchMode = [area:‘lazy‘]    Integer id;    String name;    String code;    static mapping = {        table ‘m_city‘    }}

hasMany代表CityInfo是一的一方,fetchMode配置的是抓模數式,這裡使用的是懶載入(預設)。要注意的是由於我的資料庫中對於的表為m_city;假設不配置表示對於的表為CityInfo


class AreaInfo {    static belongsTo=[city:CityInfo]    Integer id;    String name;    String areaCode;    static mapping = {        table ‘m_area‘        areaCode column:‘areaCode‘        city column: ‘cityId‘    }}

belongsTo配置的是多的一方,也就是是說AreaInfo中存在一個外鍵名稱是city.綜合上面的能夠看出CityInfo是主表,而AreaInfo是從表。這裡有點奇怪的是areaCode映射出來的列名為area_code為了方便我順便把要映射的列名改掉了


2.建立控制器和視圖

這個步驟就不說了,直接使用intellij IDE就能夠自己主動為我們組建控制器和視圖了。先來看看產生的控制器能不能用

這說明產生的控制器沒有問題,以下加入一個方法用來儲存城市和地區資訊


//儲存城市和地區資訊    @Transactional    def saveCityAndArea(){        def a=new AreaInfo()        a.setName("西山區")        a.setAreaCode("XS")        //Set<AreaInfo> s=new HashSet<AreaInfo>()       // s.add(a)        def c=new CityInfo()        c.setName("昆明市")        c.setCode("KM")        c.save()        a.setCity(c)        a.save()        render "資料儲存成功"    }

這裡要注意的是假設是關係型資料庫,那麼就不要忘記配置事務。遺憾的是級聯儲存用這個架構貌似有問題,另外要注意的是grail預設的級聯儲存和更新,可是不會串聯刪除除非配置的是雙向關聯(也配置了belongsTo).

接下來我也寫了個方法,用來查詢對於城市的地區資訊:

  //查詢城市資訊    def queryCity(){        def city=CityInfo.findById(params.id)        Set<AreaInfo> area=city.getArea()        Iterator<AreaInfo> it=area.iterator()        def buf=new StringBuffer()        while(it.hasNext()){            AreaInfo info=it.next()            buf.append(info.getName()+",")        }        render buf.toString()    }

要注意的是findBy是一個動態查詢方法,findById就表示通過Id來查詢城市資訊



grails一對多雙向關聯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.