




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、數(shù)據(jù)模型的首次迭代接下來我們要開始完成我們的博客引擎的模型部分。JPA入門模型層是一個Play應用的核心(對于其他Web框架也同樣成立)。它是一個對應用操作的資源的領域特定的表示。因為我們想要創(chuàng)建一個博客引擎,模型層就包括User,Post和Comment(用戶,博文和評論)。因為大多數(shù)模型對象需要在應用停止運行時保留下來,我們需要把它們存儲在持久性數(shù)據(jù)庫中。一個普遍的選擇是使用關系型數(shù)據(jù)庫。因為Java是一個面向?qū)ο蟮恼Z言,我們將使用一個ORM來減少一些繁瑣的工作。JPA是一個給ORM定義一套標準API的Java規(guī)范。作為一個JPA的實現(xiàn),Play使用猿媛皆知的Hibernate框架。之所以
2、使用JPA而不是原生的Hibernate API,是因為這樣所有的映射都可以用Java對象直接完成。如果之前用過Hibernate或JPA,你將驚訝于Play所添加的包裝。不再需要配置什么了;JPA與Play框架合一。如果你不知道JPA,你可以在繼續(xù)之前閱讀一些JPA實現(xiàn)的介紹User類我們首先來完成User類。創(chuàng)建新文件/yabe/app/models/User.java,并寫入下面的內(nèi)容:package models;import java.util.*;import javax.persistence.*;import play.db.jpa.*;Entitypublic class U
3、ser extends Model public String email; public String password; public String fullname; public boolean isAdmin; public User(String email, String password, String fullname) this.email = email; this.password = password; this.fullname = fullname; Entity注解(annotation)標記該類成為托管的JPA實體(managed JPA Entity),而M
4、odel父類將自動提供一些接下來將會用到的有用的JPA輔助函數(shù)。這個類的所有成員變量都會被持久化到數(shù)據(jù)庫中。默認情況下,對應的表就是'User'。如果想要使用一個'user'是保留關鍵字的數(shù)據(jù)庫,你需要給JPA映射指定一個不同的表名。要想這么做,使用Table(name="blog_user")注解User類。你的模型對象不一定得繼承自類。你也可以使用原生JPA。但繼承自該類往往是個更好的選擇,因為它使得運用JPA變得更為簡單。如果之前用過JPA,你知道每個JPA實體都需要提供一個Id屬性。在這里,Model父類已經(jīng)提供了一個自動生成的ID,
5、在大多數(shù)情況下,這樣就行了。不要認為生成的id成員變量是函數(shù)變量(functional identifier),其實它是技術變量(technical identifier)。區(qū)分這兩概念通常是個好主意,記住自動生成的ID是一個技術變量(譯注:這里我弄不懂,以下附上原文)Dont think about this provided id field as a functional identifier but as a technical identifier. It is generally a good idea to keep both concepts separat
6、ed and to keep an automatically generated numeric ID as a technical identifier.如果你寫過Java,心中可能已經(jīng)敲起了警鐘,因為我們居然大量使用公有成員!在Java(一如其他面向?qū)ο笳Z言),最佳實踐通常是盡量保持各成員私有,并提供getter和setter。這就是封裝,面向?qū)ο笤O計的基本概念之一。事實上,Play已經(jīng)考慮到這一點,在自動生成getter和setter的同時保持封裝;等下我們將看到它是怎么做到的。現(xiàn)在你可以刷新主頁面,看一下結果。當然,除非你犯錯,否則應該什么變化都看不到:D。Play自動編譯并加載了U
7、ser類,不過這沒有給應用添加任何新特性。寫下第一個測試測試新增的User類的一個好方法是寫下JUnit測試用例。它會允許你增量開發(fā)的同時保證一切安好。要運行一個測試用例,你需要在'test'模式下運行應用。停止當前正在運行的應用,打開命令行并輸入:$ play testplay test命令就像play run,不過它加載的是一個測試運行器模塊,使得你可以直接在瀏覽器中運行測試套件。當你在test mode中運行Play應用時,Play會自動切換到test框架ID并加載對應的application.conf。閱讀框架ID文檔來了解更多。在瀏覽器打開http:/localhos
8、t:9000/tests頁面來看看測試運行器。嘗試選擇所有的默認測試并運行;應該全部都會是綠色但是默認的測試其實什么都沒測:D我們將使用JUnit測試來測試模型部分。如你所見,已經(jīng)存在一個默認的BasicTests.java,所以讓我們打開它(/yabe/test/BasicTest.java):import org.junit.*;import play.test.*;import models.*;public class BasicTest extends UnitTest Test public void aVeryImportantThingToTest() assertEquals
9、(2, 1 + 1); 刪除沒用的默認測試(aVeryImportantThingToTest),創(chuàng)建一個注冊新用戶并進行檢查的測試:Testpublic void createAndRetrieveUser() / Create a new user and save it new User("bob", "secret", "Bob").save(); User bob = User.find("byEmail", "bob").first(); / Test assertNotNull(b
10、ob); assertEquals("Bob", bob.fullname);如你所見,Model父類給我們提供了兩個非常有用的方法:save()和find()。你可以在Play文檔中的JPA支持閱讀到Model類的更多方法。在test runner中選擇BasicTests.java,點擊開始,看一下是不是全都變綠了。我們將需要在User類中添加一個方法,來檢查給用戶的用戶名和密碼是否存在了。讓我們完成它,并且測試它。在User.java中,添加connect()方法:public static User connect(String email, String pass
11、word) return find("byEmailAndPassword", email, password).first();如今測試用例成這樣:Testpublic void tryConnectAsUser() / Create a new user and save it new User("bob", "secret", "Bob").save(); / Test assertNotNull(User.connect("bob", "secret"); asser
12、tNull(User.connect("bob", "badpassword"); assertNull(User.connect("tom", "secret");每次修改之后,你都可以從Play測試運行器運行所有的測試,來確保沒有什么被破壞了。Post類Post類表示博客文章。讓我們寫下代碼:package models;import java.util.*;import javax.persistence.*;import play.db.jpa.*;Entitypublic class Post exten
13、ds Model public String title; public Date postedAt; Lob public String content; ManyToOne public User author; public Post(User author, String title, String content) this.author = author; this.title = title; this.content = content; this.postedAt = new Date(); 這里我們使用Lob注解告訴JPA來使用字符大對象類型(clob)來存儲文章內(nèi)容。我們
14、也聲明跟User類的關系是ManyToOne。這意味著每個Post對應一個User,而每個User可以有多個Post。PostgreSQL的最近版本不會將Lob注解的String成員存儲成字符大對象類型,除非你額外用Type(type = "org.hibernate.type.TextType")注解該成員。我們將寫一個新的測試用例來檢查Post類能否正常工作。但在寫下更多測試之前,我們需要修改下JUnit測試類。在當前測試中,數(shù)據(jù)庫的內(nèi)容永不刪除,所以每次運行測試都會創(chuàng)建越來越多的對象。假如將來我們需要測試對象的數(shù)目是否正確,這將會是一個問題。所以先寫一個JUnit的s
15、etup()方法在每次測試之前清空數(shù)據(jù)庫:public class BasicTest extends UnitTest Before public void setup() Fixtures.deleteDatabase(); Before是JUnit測試工具的一個核心概念如你所見,F(xiàn)ixtures類是一個在測試時幫助處理數(shù)據(jù)庫的類。再次運行測試并檢查是否一切安好。之后接著下下一個測試:Testpublic void createPost() / Create a new user and save it User bob = new User("bob", "
16、secret", "Bob").save(); / Create a new post new Post(bob, "My first post", "Hello world").save(); / Test that the post has been created assertEquals(1, Post.count(); / Retrieve all posts created by Bob List<Post> bobPosts = Post.find("byAuthor", bob
17、).fetch(); / Tests assertEquals(1, bobPosts.size(); Post firstPost = bobPosts.get(0); assertNotNull(firstPost); assertEquals(bob, firstPost.author); assertEquals("My first post", firstPost.title); assertEquals("Hello world", firstPost.content); assertNotNull(firstPost.postedAt);不
18、要忘記導入,否則你會得到一個編譯錯誤。添加Comment類最后,我們需要給博文添加評論功能。創(chuàng)建Comment類的方式十分簡單直白。package models;import java.util.*;import javax.persistence.*;import play.db.jpa.*;Entitypublic class Comment extends Model public String author; public Date postedAt; Lob public String content; ManyToOne public Post post; public Comme
19、nt(Post post, String author, String content) this.post = post; this.author = author; this.content = content; this.postedAt = new Date(); 讓我們寫下第一個測試用例:Testpublic void postComments() / Create a new user and save it User bob = new User("bob", "secret", "Bob").save(); / Cre
20、ate a new post Post bobPost = new Post(bob, "My first post", "Hello world").save(); / Post a first comment new Comment(bobPost, "Jeff", "Nice post").save(); new Comment(bobPost, "Tom", "I knew that !").save(); / Retrieve all comments List&l
21、t;Comment> bobPostComments = Comment.find("byPost", bobPost).fetch(); / Tests assertEquals(2, bobPostComments.size(); Comment firstComment = bobPostComments.get(0); assertNotNull(firstComment); assertEquals("Jeff", firstComment.author); assertEquals("Nice post", firs
22、tComment.content); assertNotNull(firstComment.postedAt); Comment secondComment = bobPostComments.get(1); assertNotNull(secondComment); assertEquals("Tom", secondComment.author); assertEquals("I knew that !", secondComment.content); assertNotNull(secondComment.postedAt);你可以看到Post和
23、Comments之間的聯(lián)系并不緊密:我們不得不通過查詢來獲得所有跟某一個Post關聯(lián)的評論。通過在Post和Comment類之間建立新的關系,我們可以改善這一點。在Post類添加comments成員:.OneToMany(mappedBy="post", cascade=CascadeType.ALL)public List<Comment> comments;public Post(User author, String title, String content) ments = new ArrayList<Comment>(); this.au
24、thor = author; this.title = title; this.content = content; this.postedAt = new Date();.注意現(xiàn)在我們用mappedBy屬性來告訴JPAComment類的post成員是維持這個關系的一方。當你用JPA定義一個雙向關系時,需要指定哪一方來維持這個關系。在這個例子中,因為Comment示例依賴于Post,我們按Comment.post的反向來定義關系。我們也設置了cascade屬性來告訴JPA,我們希望Post的刪除將級聯(lián)影響到comments。也即是,如果你刪除一個博文時,所有相關的評論也將一并刪除。由于有了這個
25、新關系,我們可以給Post類添加一個輔助方法來簡化評論的添加:public Post addComment(String author, String content) Comment newComment = new Comment(this, author, content).save(); ments.add(newComment); this.save(); return this;讓我們寫多一個測試檢查它能否工作:Testpublic void useTheCommentsRelation() / Create a new user and save it User bob = ne
26、w User("bob", "secret", "Bob").save(); / Create a new post Post bobPost = new Post(bob, "My first post", "Hello world").save(); / Post a first comment bobPost.addComment("Jeff", "Nice post"); bobPost.addComment("Tom", &q
27、uot;I knew that !"); / Count things assertEquals(1, User.count(); assertEquals(1, Post.count(); assertEquals(2, Comment.count(); / Retrieve Bob's post bobPost = Post.find("byAuthor", bob).first(); assertNotNull(bobPost); / Navigate to comments assertEquals(2, bobPments.size(); ass
28、ertEquals("Jeff", bobPments.get(0).author); / Delete the post bobPost.delete(); / Check that all comments have been deleted assertEquals(1, User.count(); assertEquals(0, Post.count(); assertEquals(0, Comment.count();這次全綠了么?使用Fixtures來寫更復雜的測試當你開始寫更加復雜的測試,你通常需要一些測試數(shù)據(jù)。Fixtures允許你在一個YAML文件中描述你
29、的模型,并在測試開始前加載。編輯/yabe/test/data.yml并開始描述一個User:User(bob): email password: secret fullname: Bob.呃,因為data.yml有點大,你可以在這里下載它。現(xiàn)在我們可以創(chuàng)建一個加載數(shù)據(jù)并對它運行一些斷言的測試用例:Testpublic void fullTest() Fixtures.loadModels("data.yml"); / Count things assertEquals(2, User.count(); assertEquals(3, Post.count(); asser
30、tEquals(3, Comment.count(); / Try to connect as users assertNotNull(User.connect("bob", "secret"); assertNotNull(User.connect("jeff", "secret"); assertNull(User.connect("jeff", "badpassword"); assertNull(User.connect("tom", "secret"); / Find all of Bob's posts List<Post> bobPosts = Post.find("author.em
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 襄陽職業(yè)技術學院《醫(yī)學細胞生物學與遺傳學實驗》2023-2024學年第二學期期末試卷
- 江蘇省鹽城市阜寧中學2025屆高三下學期第二次教學質(zhì)量監(jiān)測數(shù)學試題含解析
- 山東省濰坊市壽光市2025年初三畢業(yè)考試數(shù)學試題含解析
- 山東省肥城市泰西中學2025屆高三下學期教學質(zhì)量監(jiān)測化學試題含解析
- 上海工程技術大學《院線經(jīng)營與管理》2023-2024學年第一學期期末試卷
- 六盤水幼兒師范高等專科學校《中醫(yī)藥概論》2023-2024學年第二學期期末試卷
- 金華市磐安縣2025年數(shù)學三下期末教學質(zhì)量檢測試題含解析
- 四川水利職業(yè)技術學院《鋼琴伴奏與彈唱》2023-2024學年第一學期期末試卷
- 浙江省江北區(qū)市級名校2024-2025學年語文試題基地校初三畢業(yè)班總復習平面向量、復數(shù)形成性測試卷語文試題試卷含解析
- 中國科學技術大學《移動互聯(lián)網(wǎng)應用開發(fā)技術》2023-2024學年第一學期期末試卷
- 俄羅斯介紹模板
- 50以內(nèi)加減法練習題
- 全民國家安全教育日培訓課件模板(可編輯)
- 江蘇省鹽城市建湖縣2023-2024學年七年級下學期期中語文試題
- 印刷廠常用生產(chǎn)工藝、設備作業(yè)指導書一整套
- 小班語言《輕輕地》課件
- 甘肅省農(nóng)墾集團有限責任公司人才招聘考試試題及答案
- 安全生產(chǎn)投入臺賬(模板)
- 彩色多普勒血流成像講解
- 電力配網(wǎng)安全培訓課件
- 試驗檢測單位安全培訓課件
評論
0/150
提交評論