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

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

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

    隨筆-42  評論-578  文章-1  trackbacks-0

    本期開始講Model層的開發(fā),整合iBatis框架,iBatis是Apache旗下Java數(shù)據(jù)持久層的框架,跟Hibernate是同一類型的框架。大家可到它的官方網(wǎng)站去下載http://ibatis.apache.org/java.cgi,如下圖:

    image

    我這里下載的是當(dāng)前最新版本iBatis 2.3.4 , 下載之后,解壓包是這樣的:

    image

    我們在lib目錄下,找到“ibatis-2.3.4.726.jar”文件,加入到我們項目的lib目錄下,就行。在這里,我們先說下怎么學(xué)習(xí)這個iBatis框架:上圖中,有個simple_example的文件夾,它里面就包含了一個超級簡單且容易理解的例子,大家可以去學(xué)習(xí)一下。By the way,如果你學(xué)過Hibernate的話,你會發(fā)覺iBatis要比Hibernate好學(xué)很多。關(guān)于Hibernate和iBatis的爭論,網(wǎng)上有很多,大家有興趣可以去了解一下。

    好,我們先建立數(shù)據(jù)庫和設(shè)計數(shù)據(jù)庫吧。我這項目用的是MySQL 5.0。生成數(shù)據(jù)庫和數(shù)據(jù)表的SQL語句如下:

    create database simpledb;

    create table article
    (
        ID int auto_increment not null primary key,
        TITLE varchar(25),
        AUTHOR varchar(25),
        CONTENT text,
        PUBTIME date
    );

     

    這是我們常見的新聞表及其中的字段。

    接下來,寫一個與表對應(yīng)的新聞類,Article.java,這個其實是POJO類,代碼如下:

    package cn.simple.pojo;

    import java.util.Date;

    public class Article {
        
        
    private int id;
        
    private String title;
        
    private String author;
        
    private String content;
        
    private Date pubtime;
        
        
    /***********getter和setter方法***********/
        
    public int getId() {
            
    return id;
        }

        
    public void setId(int id) {
            
    this.id = id;
        }

        
    public String getTitle() {
            
    return title;
        }

        
    public void setTitle(String title) {
            
    this.title = title;
        }

        
    public String getAuthor() {
            
    return author;
        }

        
    public void setAuthor(String author) {
            
    this.author = author;
        }

        
    public String getContent() {
            
    return content;
        }

        
    public void setContent(String content) {
            
    this.content = content;
        }

        
    public Date getPubtime() {
            
    return pubtime;
        }

        
    public void setPubtime(Date pubtime) {
            
    this.pubtime = pubtime;
        }

        
    }

     

    有了數(shù)據(jù)表和實體類,現(xiàn)在來寫兩者之間映射的配置文件Article.xml。代碼如下:

    <?xml version="1.0" encoding="UTF-8" ?>

    <!DOCTYPE sqlMap      
        PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
        "http://ibatis.apache.org/dtd/sql-map-2.dtd"
    >

    <sqlMap namespace="Article">

        
    <!-- Use type aliases to avoid typing the full classname every time. -->
        
    <typeAlias alias="Article" type="cn.simple.pojo.Article" />

        
    <!--
            Result maps describe the mapping between the columns returned from a
            query, and the class properties. A result map isn't necessary if the
            columns (or aliases) match to the properties exactly.
        
    -->
        
    <resultMap id="ArticleResult" class="Article">
            
    <result property="id" column="ID" />
            
    <result property="title" column="TITLE"/>
            
    <result property="author" column="AUTHOR"/>
            
    <result property="content" column="CONTENT"/>
            
    <result property="pubtime" column="PUBTIME"/>
        
    </resultMap>

        
    <!--
            Select with no parameters using the result map for Account class.
        
    -->
        
    <select id="selectAllArticles" resultMap="ArticleResult">
            select * from article
          
    </select>

        
    <!--
            A simpler select example without the result map. Note the aliases to
            match the properties of the target result class.
        
    -->
        
    <select id="selectArticleById" parameterClass="int" resultClass="Article">
            select
            ID as id,
            TITLE as title,
            AUTHOR as author,
            CONTENT as content,
            PUBTIME as pubtime
            from Article
            where ID=#id#
      
    </select>

        
    <!-- Insert example, using the Account parameter class -->
        
    <insert id="insertArticle" parameterClass="Article">
            insert into article (
                TITLE,
                AUTHOR,
                CONTENT,
                PUBTIME
            ) values (
                #title#,
                #author#,
                #content#,
                #pubtime#
            )
      
    </insert>

        
    <!-- Update example, using the Account parameter class -->
        
    <update id="updateArticle" parameterClass="Article">
            update article set
            TITLE = #title#,
            AUTHOR = #author#,
            CONTENT = #content#,
            PUBTIME = #pubtime#
            where
            ID = #id#
      
    </update>

        
    <!-- Delete example, using an integer as the parameter class -->
        
    <delete id="deleteArticleById" parameterClass="int">
            delete from article where ID = #id#
      
    </delete>

    </sqlMap>

     

    大家不要覺得這個映射文件很復(fù)雜,其實,這挺容易理解的,如果大家賴得寫的話,可復(fù)制iBatis自帶的simple_example下的例子的映射文件,然后修改一下就行。

    有了表、實體類、表與實體之間的映射文件,之后,該做什么呢?學(xué)過Hibernate的朋友會想到那個數(shù)據(jù)庫連接信息的配置文件,當(dāng)然,iBatis也需要類似的文件,即SqlMapConfig.xml,代碼如下:

    <?xml version="1.0" encoding="UTF-8" ?>

    <!DOCTYPE sqlMapConfig      
        PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
        "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"
    >

    <sqlMapConfig>

      
    <!-- Configure a built-in transaction manager.  If you're using an 
           app server, you probably want to use its transaction manager 
           and a managed datasource 
    -->
      
    <transactionManager type="JDBC" commitRequired="false">
        
    <dataSource type="SIMPLE">
          
    <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
          
    <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/simpledb"/>
          
    <property name="JDBC.Username" value="root"/>
          
    <property name="JDBC.Password" value="root"/>
        
    </dataSource>
      
    </transactionManager>

      
    <!-- List the SQL Map XML files. They can be loaded from the 
           classpath, as they are here (com.domain.data
    -->
      
    <sqlMap resource="cn/simple/pojo/Article.xml"/>
      
    <!-- List more here
      <sqlMap resource="com/mydomain/data/Order.xml"/>
      <sqlMap resource="com/mydomain/data/Documents.xml"/>
      
    -->

    </sqlMapConfig>

     

    一看這代碼,也有點復(fù)雜,我的說法同上,大不了COPY,再略作修改,呵呵

    好了,來寫我們的業(yè)務(wù)邏輯層:

     

    package cn.simple.manager;

    import java.io.IOException;
    import java.io.Reader;
    import java.sql.SQLException;
    import java.util.List;
    import cn.simple.pojo.Article;
    import com.ibatis.common.resources.Resources;
    import com.ibatis.sqlmap.client.SqlMapClient;
    import com.ibatis.sqlmap.client.SqlMapClientBuilder;

    public class ArticleManager {

        
    /**
         * SqlMapClient instances are thread safe, so you only need one. In this
         * case, we'll use a static singleton. So sue me. ;-)
         
    */

        
    private static SqlMapClient sqlMapper;

        
    /**
         * It's not a good idea to put code that can fail in a class initializer,
         * but for sake of argument, here's how you configure an SQL Map.
         
    */

        
    static {
            
    try {
                Reader reader 
    = Resources.getResourceAsReader("SqlMapConfig.xml");
                sqlMapper 
    = SqlMapClientBuilder.buildSqlMapClient(reader);
                reader.close();
            }
     catch (IOException e) {
                
    // Fail fast.
                throw new RuntimeException(
                        
    "Something bad happened while building the SqlMapClient instance."
                                
    + e, e);
            }

        }


        
    /**
         * 查詢列表
         * 
    @return
         * 
    @throws SQLException
         
    */

        
    public static List<Article> selectAllArticles() throws SQLException {
            
    return sqlMapper.queryForList("selectAllArticles");
        }

        
        
    /**
         * 插入數(shù)據(jù)
         * 
    @param article
         * 
    @throws SQLException
         
    */

        
    public static void insertArticle(Article article) throws SQLException {
            sqlMapper.insert(
    "insertArticle", article);
        }

        
        
    /**
         * 更新數(shù)據(jù)
         * 
    @param article
         * 
    @throws SQLException
         
    */

        
    public static void updateArticle(Article article) throws SQLException {
            sqlMapper.update(
    "updateArticle", article);
        }


        
    /**
         * 刪除數(shù)據(jù)
         * 
    @param id
         * 
    @throws SQLException
         
    */

        
    public static void deleteArticle(int id) throws SQLException {
            sqlMapper.delete(
    "deleteArticleById", id);
        }

        
        
    /**
         * 單查數(shù)據(jù)
         * 
    @param id
         * 
    @return
         * 
    @throws SQLException
         
    */

        
    public static Article queryArticleById(int id) throws SQLException {
            Article article 
    = (Article)sqlMapper.queryForObject("selectArticleById", id);
            
    return article;
        }


    }

     

    寫一個Junit測試類來測試一下吧,代碼如下:

    package cn.simple.manager;

    import java.sql.SQLException;
    import java.util.Date;
    import java.util.List;
    import org.junit.Test;
    import cn.simple.pojo.Article;

    public class ArticleManagerTest {

        @Test
        
    public void testSelectAllArticles() throws SQLException {
            List
    <Article> list = ArticleManager.selectAllArticles();
            
    for(Article a : list){
                System.out.println(a.getTitle() 
    + a.getAuthor() + a.getContent() + a.getPubtime());
            }

        }


        @Test
        
    public void testInsertArticle() throws SQLException {
            
    for(int i=0; i<10; i++){
                Article article 
    = new Article();
                article.setTitle(
    "title-" + i);
                article.setAuthor(
    "author-" + i);
                article.setContent(
    "content-" + i);
                article.setPubtime(
    new Date());
                ArticleManager.insertArticle(article);
            }

        }


        @Test
        
    public void testUpdateArticle() throws SQLException {
            Article article 
    = new Article();
            article.setId(
    3);
            article.setTitle(
    "title-title");
            article.setAuthor(
    "author-author");
            ArticleManager.updateArticle(article);
        }


        @Test
        
    public void testDeleteArticle() throws SQLException {
            ArticleManager.deleteArticle(
    5);
        }


    }

     

    到此,我們的項目文件列表截圖如下:

    image

    新聞管理的Model層開發(fā)完畢,可以供我們的Action調(diào)用了,好,Struts 2.1.6 精簡實例系列教程,敬請大家期待下文!



    本文原創(chuàng),轉(zhuǎn)載請注明出處,謝謝!http://www.tkk7.com/rongxh7(心夢帆影JavaEE技術(shù)博客)
        

    posted on 2009-07-26 03:02 心夢帆影 閱讀(3601) 評論(9)  編輯  收藏 所屬分類: Struts2.1.6系列教程

    評論:
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-26 12:02 | 小人物
    太牛了。。。  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis)[未登錄] 2009-07-26 16:26 | 小毅
    牛倒不覺得。。寫的還不錯 加油  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-26 19:34 | shivaree
    嗯,做教程的話還是把標(biāo)簽含義講解下比較好。
    尤其是映射文件 , 各個框架設(shè)計不一樣 。  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-26 21:08 | ppq
    用Ibatis的話,一般用自動生成工具來生成映射文件,這樣才比較方便,不然容易寫錯。  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-26 23:08 | ynyee
    好的很,對于一個新手來說,稍微有點少,不過還是很狠狠好的,豐收了~支持~支持到底,從老大的編碼風(fēng)格來看,是一名高手高手高高手~  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-26 23:45 | 心夢帆影
    @shivaree
    嗯,你說得對,我以后會注意得,講解詳細(xì)點!  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-07-29 13:55 | 身在半空
    感謝樓主。  回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2009-08-27 09:39 | tcftt
    十分感謝樓主的教程!

    對我受益非淺,并從樓主的教程中看到我一直期待的東東。

    繼續(xù)加油啊!
      回復(fù)  更多評論
      
    # re: Struts 2.1.6 精簡實例系列教程(3):新聞管理Model層的開發(fā)(整合iBatis) 2011-04-28 00:44 | struts
    太厲害了!期待您下次的教導(dǎo)!謝謝!  回復(fù)  更多評論
      
    主站蜘蛛池模板: 国产精品成人四虎免费视频| 日日麻批免费40分钟无码| 亚洲欧美精品午睡沙发| 亚洲制服丝袜第一页| 亚洲 欧洲 日韩 综合在线| 亚洲Av无码一区二区二三区| 亚洲另类精品xxxx人妖| 亚洲娇小性xxxx| 亚洲综合中文字幕无线码| 亚洲午夜无码毛片av久久京东热| 亚洲伊人久久精品| 国产精品亚洲片在线va| 亚洲欧美国产精品专区久久| 色综合久久精品亚洲国产| 日本精品久久久久久久久免费 | 日韩一级视频免费观看| 国产高清视频在线免费观看| 亚洲 无码 在线 专区| 国产亚洲精品成人a v小说| 亚洲精品tv久久久久久久久| 亚洲视频.com| ww亚洲ww在线观看国产| 亚洲国产成人精品无码区花野真一| 黑人粗长大战亚洲女2021国产精品成人免费视频 | 亚洲一区二区观看播放| 久久综合亚洲色hezyo| 一级毛片免费不卡| 国产免费无码AV片在线观看不卡| 日韩免费无码一区二区三区| 免费下载成人电影| 国产免费私拍一区二区三区| 亚洲精品A在线观看| 久久亚洲国产视频| 久久亚洲精品专区蓝色区| 美女裸体无遮挡免费视频网站| 国产一二三四区乱码免费| 2021国内精品久久久久精免费| 好爽又高潮了毛片免费下载 | 国产成人福利免费视频| 日日操夜夜操免费视频| 国产亚洲成归v人片在线观看|