初学ibatis

1.下载ibatis-2.3.0.677.jar,数据库mysql-connector-java-5.1.5-bin.jar包

mysql下的sql语句:

use test;
create table User(
 id int auto_increment primary key,
 userName varchar(20),
 userPwd varchar(20),
 userAddr varchar(100)
);

insert into User values(null,'hello1','hello1pwd','address1');
insert into User values(null,'hello2','hello2pwd','address2');
insert into User values(null,'hello3','hello3pwd','address3');
commit;


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/test"/>
      <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="wang/mydomain/User.xml"/>
  <!-- List more here...
  <sqlMap resource="com/mydomain/data/Order.xml"/>
  <sqlMap resource="com/mydomain/data/Documents.xml"/>
  -->

</sqlMapConfig>

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="wang.mydomain.User"/>

  <!-- 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="AccountResult" class="User">
    <result property="id" column="id"/>
    <result property="userName" column="userName"/>
    <result property="userPwd" column="userPwd"/> 
    <result property="userAddr" column="userAddr"/> 
  </resultMap>

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

  <!-- A simpler select example without the result map.  Note the
       aliases to match the properties of the target result class. -->
  <select id="selectAccountById" parameterClass="int" resultClass="User">
    select
      id as id,
      userName as userName,
      userPwd as userPwd,
      userAddr as userAddr
    from User
    where id = #id#
  </select>
  
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertAccount" parameterClass="User">
    insert into User (
      id,
      userName,
      userPwd,
      userAddr
      )
    values (
      #id#, #userName#, #userPwd#, #userAddr#
    )
  </insert>

  <!-- Update example, using the Account parameter class -->
  <update id="updateAccount" parameterClass="User">
    update User set
      id = #id#,
      userName = #userName#,
      userPwd = #userPwd#
    where
      id = #id#
  </update>

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

</sqlMap>

User.java文件:

package wang.mydomain;

public class User {

  private int id;
  private String userName;
  private String userPwd;
  private String userAddr;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getUserPwd() {
  return userPwd;
 }
 public void setUserPwd(String userPwd) {
  this.userPwd = userPwd;
 }
 public String getUserAddr() {
  return userAddr;
 }
 public void setUserAddr(String userAddr) {
  this.userAddr = userAddr;
 }
 
 
 
 
}

调用例子文件SimpleExample.java

package wang.mydomain;

 

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

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


/**
 * This is not a best practices class.  It's just an example
 * to give you an idea of how iBATIS works.  For a more complete
 * example, see JPetStore 5.0 at http://www.ibatis.com.
 */
public class SimpleExample {

  /**
   * 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("wang/mydomain/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);
    }
  }

  public static List selectAllAccounts () throws SQLException {
    return sqlMapper.queryForList("selectAllAccounts");
  }

  public static User selectAccountById  (int id) throws SQLException {
    return (User) sqlMapper.queryForObject("selectAccountById", id);
  }

  public static void insertAccount (User user) throws SQLException {
    sqlMapper.insert("insertAccount", user);
  }

  public static void updateAccount (User user) throws SQLException {
    sqlMapper.update("updateAccount", user);
  }

  public static void deleteAccount (int id) throws SQLException {
    sqlMapper.delete("deleteAccountById", id);  //修改过的
  }

 
  public static void main(String[] args) throws Exception{
 //select all
   List list = selectAllAccounts();
   for(int i=0;i<list.size(); i++){
    User user = (User)list.get(i);
    System.out.println(""+user.getId()+" ;"+user.getUserName()+" ;"+user.getUserPwd()+" ;"+user.getUserAddr());
   }
  
   //select(int)
   User user2 = selectAccountById(2);
   System.out.println("查找到的user="+user2.getId()+" ;"+user2.getUserName()+" ;"+user2.getUserPwd()+" ;"+user2.getUserAddr());
  
  
   //insert ok
//   User user3 = new User();
//   user3.setUserName("hello4");
//   user3.setUserPwd("hello4pwd");
//   user3.setUserAddr("address4");
//  
//   insertAccount(user3);
  
   //update ok
   User user4 = new User();
   user4.setId(4);
   user4.setUserName("upd_hello4");
   user4.setUserPwd("upd_hello4pwd");
   user4.setUserAddr("upd_address4");
   updateAccount(user4);
  
   //delete ok
   deleteAccount(4);
  
  }
}

 

备注:Oracle连接字符串:

一.连接oracle数据库
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String url="jdbc:oracle:thin:@服务器ip:1521:数据库名称";
    Connection conn=DriverManager.getConnection(url,"用户名","密码");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值