<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    大漠駝鈴

    置身浩瀚的沙漠,方向最為重要,希望此blog能向大漠駝鈴一樣,給我方向和指引。
    Java,Php,Shell,Python,服務器運維,大數據,SEO, 網站開發、運維,云服務技術支持,IM服務供應商, FreeSwitch搭建,技術支持等. 技術討論QQ群:428622099
    隨筆 - 238, 文章 - 3, 評論 - 117, 引用 - 0
    數據加載中……

    A Blog Application with Warp (continued)(3)

    A Blog Application with Warp (continued)

    First check out the previous tutorial on creating a Blog application to get yourself going. In that article, you saw how to add forms and a bit of interactivity. In this one, I'll demonstrate integration of Warp-persist, the JPA/Hibernate module. It is worthwhile reading the introduction to the Warp-persist module first. You will learn the following Warp concepts:

    The first thing to do is modify our data model POJO (Blog) and make it a mapped JPA entity:

    @Entity
    public class Blog {
    private Long id;
    private String subject;
    private String text;
     

    @Id @GeneratedValue
    public Long getId() {
    return id;

    //rest of the getters/setters + equals() + hashCode()

    }

    The most obvious addition here is that of a surrogate key, a Long field id that represents the identity of the object. We have also marked its getter as the identity and the class itself as a JPA entity with the @Id and @Entity annotations respectively.

    Remember that you absolutely must override equals() and hashCode() -- this is done by simply returning the equals and hashCode of the id field. It is a poor programming practice to create data model objects and not define equals() and hashCode() for them, it will lead to all kinds of problems if you do not.

    OK, let's drop in a simple persistence.xml into our /META-INF directory so that Hibernate knows our configuration. I've stolen this from the Warp-persist guide:

    <?xml version="1.0" encoding="UTF-8" ?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <!-- A JPA Persistence Unit -->
    <persistence-unit name="blogJpaUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
     
    		<!-- JPA entities must be registered here -->
    <class>com.wideplay.misc.blog.Blog</class>

    <properties>
    			<!-- vendor-specific properties go here -->
    </properties>
    </persistence-unit>

    </persistence>

    Not much to notice here except that Hibernate is our persistence provider and we're using RESOURCE_LOCAL transactions. Inside the <properties> tag, however, you need to place all your configuration options (for whatever JPA vendor you choose). For Hibernate, mine looks like the following:

    <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
    <property name="hibernate.connection.url" value="jdbc:hsqldb:file:C:/temp/hsqltmp"/>
    <property name="hibernate.connection.username" value="sa"/>
    <property name="hibernate.connection.password" value=""/>
    <property name="hibernate.connection.pool_size" value="1"/>
    <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

    <property name="hibernate.current_session_context_class" value="thread"/>
    <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
    <property name="hibernate.hbm2ddl.auto" value="create"/>

     Again, it is mostly boilerplate. Never use this configuration directly in production, the following things that it assumes are almost certainly not what you will want in a real-world application:

    • Im using HSQLDB (a temporary in-memory database)
    • I am using Hibernate's default connection pool
    • I am creating the schema every time Hibernate starts up (hbm2ddl.auto=create)
    • I am not using any second-level cache

    Otherwise everything is fine. The session-context strategy is set to thread meaning that the current thread (in our case, that associated with a request) will be used as the context for an EntityManager. So different requests will see different EntityManagers.

    Now, we need to tell Warp that the persistence service is ready for use. This is done in the WarpModule (which you should remember from the Hello World example). This is roughly how your WarpModule should look:

    public class BlogModule implements WarpModule {

    public void configure(Warp warp) {
    warp.install(PersistenceService
    .usingJpa()
    .across(UnitOfWork.TRANSACTION)
    .buildModule()
    );

    warp.install(new AbstractModule() {
    protected void configure() {
    bindConstant().annotatedWith(JpaUnit.class)
    .to("blogJpaUnit");
    }
    });

    warp.addStartupListener(BlogStartupListener.class);
    }
    }

     And implement the startup listener to do some initialization work:

       public class BlogStartupListener implements StartupListener {
    @Inject PersistenceService service;

    public void onStartup() {
    service.start();
    }
    }

     This tells Warp-persist to start up JPA and make the persistence layer ready when Warp starts up. Likewise, you must tell Warp when to shutdown too (services like connection pools require explicit shutdowns):

       public class BlogShutdownListener implements ShutdownListener {
    @Inject EntityManagerFactory emf;

    public void onShutdown() {
    emf.close();
    }
    }

     Don't forget to add the BlogShutdownListener in your WarpModule configuration. You do not need to release any Warp resources explicitly (Warp acts on the Java Servlet destroy event).

    OK, wow, we're done a lot of setup work. Let's actually convert our blog's pages to use all this neat configuration. First the ListBlogs page:

    @URIMapping("/home")
    public class ListBlogs {
    @Finder(query = "from Blog", returnAs = ArrayList.class)
    public Collection<Blog> getBlogList() {
    return null;
    }
    }

     It looks completely different now! What happened? We've done a few things:

    • Gotten rid of the HashMap and @Singleton scoping
    • Converted our property getter for the blog list into a Dynamic Finder
    • Implemented a dummy stub for the Dynamic Finder

    The finder will be intercepted by warp-persist and replaced with the query provided in the @Finder annotation. In this case, we're selecting every Blog available in the persistent store and returning them as an ArrayList.

    Now lets do the Read page, this is similarly very simple. We will use a Dynamic Finder encapsulated in our @PreRender event handler method:

    @URIMapping("/blog/{id}")
    public class ViewBlog {
    private Blog blog;

    @Finder(query = "from Blog where id = :id")
    Blog fetchBlog(@Named("id") String id) {
    return null;
    }

    @OnEvent @PreRender @Transactional
    public void onView(String id) {
    this.blog = fetchBlog(Long.valueOf(id)); //dangerous, validate id first!
    }
    }

    Neat, because the page objects are managed by guice, dynamic dispatch will ensure that calling fetchBlog() invokes the intercepted Dynamic Finder instead of our dummy stub which returns null. It is important to make the @PreRender event handler transactional because we are using a session-per-transaction strategy. Let's do the same with ListBlogs too:

    @URIMapping("/home")
    public class ListBlogs {
    @Transactional
    @Finder(query = "from Blog", returnAs = ArrayList.class)
    public Collection<Blog> getBlogList() {
    return null;
    }
    }

    Typically we would prefer to encapsulate data access into an Accessor (Dao) style object. and run transactions on much coarser grained boundaries. But since our use case is very simple, I will leave it to your imagination to separate data access into its own semantic module/layer.

    Lastly for the good part: storing new blogs!

    @URIMapping("/blogs/compose")
    public class ComposeBlog {
    @Inject @Page private ListBlogs listBlogsPage;

    @Inject private Provider<EntityManager> em;

    private Blog newBlog = new Blog("", ""); //an empty blog

    @OnEvent @Transactional
    public ListBlogs save() {
    //save the new blog!
    em.get().persist(newBlog);

    //return to the list page
    return listBlogsPage;
    }

    public Blog getNewBlog() {
    return newBlog;
    }
    }

    This is fairly straightforward and should not need much explanation. We associate the new blog entity with the EntityManager by calling persist() and ensure that the button event handler is transactional.

    There is almost no change to the templates themselves, except that now we have switched the identity of our data object Blog to use a surrogate key. Let's use that key to reference blogs in our ListBlogs.html template:

    <?xml version="1.0" encoding="UTF-8"?>
    <html xmlns:w="http://www.wideplay.com/warp/schema/warp_core.xsd"
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="en" lang="en">

    <head w:component="meta">
    <title>Warp :: List Blogs</title>
    </head>

    <body w:component="frame">
    <h1>A list of blog entries</h1>

    <table w:component="table" w:items="${blogList}">
    <td w:component="column" w:property="subject">
    <a w:component="hyperlink" w:target="blog" w:topic="${id}">
    ${subject}
    </a>
    </td>
    </table>

    <a href="blogs/compose">compose new entry</a>

    </body>
    </html>
    And that's it!

    posted on 2009-02-17 16:31 草原上的駱駝 閱讀(247) 評論(0)  編輯  收藏


    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 亚洲视频免费播放| 久久亚洲中文字幕精品有坂深雪| 亚洲av成人一区二区三区| 久久综合国产乱子伦精品免费| 亚洲av永久无码精品古装片| 久久成人免费大片| 337p日本欧洲亚洲大胆色噜噜 | 日韩电影免费观看| 久久水蜜桃亚洲av无码精品麻豆| 色欲A∨无码蜜臀AV免费播 | 一级毛片免费在线播放| 亚洲乱码无码永久不卡在线 | 最好免费观看韩国+日本| 豆国产96在线|亚洲| 亚洲国产主播精品极品网红| 精精国产www视频在线观看免费| 国精无码欧精品亚洲一区| 久久久久免费精品国产小说| 亚洲国产成人久久三区| 国外成人免费高清激情视频 | 国产亚洲精品美女2020久久| 久久亚洲欧洲国产综合| 91老湿机福利免费体验| 亚洲 欧洲 自拍 另类 校园| 免费日本黄色网址| 成人爽a毛片免费| 亚洲最大成人网色香蕉| 亚洲精品成人a在线观看| 亚洲电影免费在线观看| 亚洲av永久中文无码精品综合| 亚洲日本va午夜中文字幕久久 | 猫咪社区免费资源在线观看 | 亚洲白嫩在线观看| 国产精品免费视频播放器| 国产在线国偷精品免费看| 国产v亚洲v天堂a无| 亚洲国产综合无码一区二区二三区| 午夜网站在线观看免费完整高清观看| 色婷五月综激情亚洲综合| 亚洲日韩中文在线精品第一 | 中文字幕免费在线播放|