欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IBATIS简单操作

程序员文章站 2022-06-09 10:07:29
...
1创建数据库
create table user
(
 id int auto_increment primary key,
 username varchar(32),
 password varchar(32)
);

select * from user;


2
添加IBATIS的jar包;

3添加配置文件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>

  <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/mydb"/>
      <property name="JDBC.Username" value="root"/>
      <property name="JDBC.Password" value="admin"/>
    </dataSource>
  </transactionManager>

  <sqlMap resource="com/wangyu/data/User.xml"/>
</sqlMapConfig>


4实体类User.java
package com.wangyu.domain;
public class User {
	private Integer id;
	private String username;
	private String password;
	// Constructors
	public User() {
	}
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return this.username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return this.password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


5对应的.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="com.wangyu.domain.User"/>

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllUsers" resultClass="User">
    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="selectUserById" parameterClass="int" resultClass="User">
    select
      id as id,username as UserName ,password as Password
    from user
    where id = #id#
  </select>
   
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertUser" parameterClass="User">
    insert into user (username,password) values (#username#,#password#)
  </insert>

  <!-- Update example, using the Account parameter class -->
  <update id="updateUser" parameterClass="User" >
    update user set username = #username#,password=#password# where id = #id#
  </update>

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

</sqlMap>


6.DAO类SimpleExample
package com.wangyu.data;

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;
import com.wangyu.domain.User;

public class SimpleExample {

	  private static SqlMapClient sqlMapper;

	  static {
	    try {
	      Reader reader = Resources.getResourceAsReader("com/wangyu/data/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<User> selectAllUser () throws SQLException {
	    return sqlMapper.queryForList("selectAllUsers");
	  }

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

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

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

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

}


7.测试类
package com.wangyu.data;

import java.util.Iterator;
import java.util.List;

import com.wangyu.domain.User;

public class Test {

	public static void main(String[] args)throws Exception {
		User u =new User();
		
		//添加用户
//		for (int i =1;i<10;i++){
//			u.setPassword("password"+i);
//			u.setUsername("username"+i);
//			SimpleExample.insertUser(u);
//		}
		
		//删除用户 -->没有不会抛出异常
		SimpleExample.deleteUser(2);
		
		//修改用户
		User user =SimpleExample.selectUserById(6) ;
		user.setPassword("zhuangsan");
		user.setUsername("zhangsan");
		SimpleExample.updateUser(user);
		//System.out.println(user.getPassword());
		
		//查询所有用户
		List<User> list = SimpleExample.selectAllUser();
		Iterator<User> rt=list.iterator();
		while(rt.hasNext()){
			User us = (User)rt.next();
			System.out.println(us.getId()+"--->"+us.getPassword()+"--->"+us.getUsername());
		}
		
		//按id查询 -->没有数据 -->空指针异常
		User us = SimpleExample.selectUserById(6);
		System.out.println(us.getUsername());
	}

}

----------------------------------------------------------------------------------------------------------------------------------------------------------

iBATIS声明事事务
	public static void insertUser(User user){
		try {
			sqlMapper.startTransaction();
			sqlMapper.insert("insertUser", user);
			sqlMapper.commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				sqlMapper.endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}