第一個通過的ibatis操作mysql的實際例子

來源:互聯網
上載者:User

參考地址:http://kin111.blog.51cto.com/738881/168984/

 

步驟如下:
1,在eclipse中建立一個工程ibatisnew,然後把mysql和ibatis的jar包匯入進去。這兩個包(ibatis-2.3.4.726.jar+mysql-connector-java-5.0.8-bin.jar)可以從網上下載,直接拷貝到WEB-INF/lib目錄下。

2,建立SqlMapConfig.xml檔案
這個檔案包含了資料庫的配置,和各個資料表對應的xml的引用部分。

檔案名稱: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://127.0.0.1:3306/db"/>
      <property name="JDBC.Username" value="root"/>
      <property name="JDBC.Password" value=""/>
    </dataSource>
  </transactionManager>

  <!-- List the SQL Map XML files. They can be loaded from the
       classpath, as they are here (com.domain.data...) -->
  <sqlMap resource="test_ibatis/User.xml"/>

</sqlMapConfig>

3,建立SqlMapConfig.xml中引用的User.xml檔案,
這個檔案對應資料庫中的user表,在這個檔案中可以定義別名,可以寫sql語句。

檔案名稱:User.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="User">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="User" type="test_ibatis.User"/>

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllUsers" resultClass="User">
    select * from user
  </select>

</sqlMap>

4,建立user.xml檔案中指定的class的檔案
這個檔案就是一個javabean,和資料庫的表的欄位相對應,有set和get方法。

檔案名稱;User.java
檔案內容:
package test_ibatis;

import java.sql.Date;

public class User {
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        String str = "id = " + this.id;
        str += " name = " + this.name;
        str += " birthday = " + this.birthday;
        str += " money = " + this.money;
        return str;
    }

    private int id;
    private String name;
    private Date birthday;
    private float money;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }
}

5,建立DAO程式和實現程式
介面名:IUserDAO.java
內容:
package test_ibatis;

import java.util.List;

public interface IUserDAO {
    public List<User> getAllUser();
}

實作類別:IUserDAOImpl.java
內容:
package test_ibatis;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class IUserDAOImpl implements IUserDAO {

    private static SqlMapClient client = null;
   
    static {
        try {
            Reader reader = Resources.getResourceAsReader("test_ibatis/SqlMapConfig.xml");
            client = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    public List<User> getAllUser() {
        // TODO Auto-generated method stub
        try {
            return client.queryForList("selectAllUsers");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

1,實作類別中要使用ibatis提供的功能,先從xml檔案中讀取配置,構造SqlMapClient的對象。
2,具體的實現方法,通過調用SqlMapClient提供的方法,指定xml中的id即可執行對應的sql,並返回結果。

6,測試class
檔案名稱:UserDAO.java
檔案內容:
package test_ibatis;

public class UserDAO {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        IUserDAO dao = new IUserDAOImpl();
        for (User user : dao.getAllUser()) {
            System.out.println(user);
        }
       
    }
}

 

7,sql建表和測試資料user.sql

drop table user;
create table `db`.`User`(
`id` int,
`name` VARCHAR(50) ,
`birthday` date,
`money` float
 );
 
 --填充資料
 insert user(id,name,birthday,money) values (1,'zhangsha','1985-01-01',50.0);
 insert user(id,name,birthday,money) values (1,'lisi','2009-06-20',470.0);
 insert user(id,name,birthday,money) values (1,'shenqi','2009-06-20',500.0);
 insert user(id,name,birthday,money) values (1,'gaojiu','2009-06-20',1000.0);
 insert user(id,name,birthday,money) values (1,'gaojiu','2009-06-20',500.0);
--查詢結果
 select * from user;

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.