Home Database Mysql Tutorial iBatis初步认识与使用

iBatis初步认识与使用

Jun 07, 2016 pm 04:12 PM
ibatis Task use

实习期间在做任务的时候需要用到ibatis,公司系统所用框架是经理搭建的,也就是说我只要把ibatis的原理与用法搞定就行了,于是我一边看着系统的代码一边在网上搜索ibaits的demo!下面就把我对ibatis的初步认识写出来,欢迎大牛提出批评与建议! iBATIS一词来

实习期间在做任务的时候需要用到ibatis,公司系统所用框架是经理搭建的,也就是说我只要把ibatis的原理与用法搞定就行了,于是我一边看着系统的代码一边在网上搜索ibaits的demo!下面就把我对ibatis的初步认识写出来,欢迎大牛提出批评与建议!

iBATIS一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2002年发起的开放源代码项目。于2010年6月16号被谷歌托管,改名为MyBatis。是一个基于SQL映射支持Java和·NET的持久层框架。(百度百科-_-!!!),当我看到持久层框架的时候,我想到了hibernate,hibernate的使用我略知一二,难道它跟hibernate的使用有相同之处吗?

下面是ibatis的框架图:

\

我仔细的分析了下:

从上往下看,是不是可以这样理解,ibatis使用SqlMap.xml和SqlMapConfig.xml这两个配置文件完成对数据库的链接和各种JDBC操作呢?

从左往右看,是不是可以这样理解,可以把各种请求与参数通过javaBean、map、primitive和xml发送,然后再将结果一一的返回给他们呢?

有了猜测,接下来就是验证的时候了,我迫不及待的找了好多demo,通过这些demo我搭建了自己的demo。

首先是数据库部分

\

接下来就是数据表对应的实体类了BookInfo.java

package com.wxc.bean;

public class BookInfo {
	private int id;
	private String bookISBN;
	private String bookName;
	private String author;
	private float price;
	private int typeId;
	private String publish;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getBookISBN() {
		return bookISBN;
	}
	public void setBookISBN(String bookISBN) {
		this.bookISBN = bookISBN;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public int getTypeId() {
		return typeId;
	}
	public void setTypeId(int typeId) {
		this.typeId = typeId;
	}
	public String getPublish() {
		return publish;
	}
	public void setPublish(String publish) {
		this.publish = publish;
	}
	@Override
	public String toString() {
		return "BookInfo:"+this.bookName+","+this.author+","+this.price+","+this.publish;
	}
}
Copy after login
像hibernate一样它也有一个对应的映射文件BookInfo.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>  
    <!-- 通过typeAlias使得我们在下面使用BookInfo实体类的时候不需要写包名 -->  
    <typeAlias alias="BookInfo" type="com.wxc.bean.BookInfo" />
    
    <!-- 只需要在这里写sql语句参数什么的可以外部传进来 -->  
    <!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->  
    <select id="listBookInfo" resultClass="BookInfo">  
        select * from bookinfo  
    </select>  
  
    <!-- parameterClass表示参数的内容 -->  
    <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->  
    <select id="listBookInfoByAuthor" parameterClass="String" resultClass="BookInfo">  
       select * from bookinfo where author = #name#
    </select>  
  	
  	<!-- 修改 -->
  	<update id="update" parameterClass="BookInfo">
  	update bookinfo set 
  	bookISBN=#bookISBN#,
  	bookName=#bookName#,
  	author=#author#,
  	price=#price#,
  	typeId=#typeId#,
  	publish=#publish# 
  	where id=#id#
  	</update>
  	
  	<!-- 删除 -->
  	<delete id="delete" parameterClass="int">
  	delete from bookinfo where id = #id#
  	</delete>
  	
  	<!-- 多条件查询 -->
  	<select id="listByAuthorAndPublis" parameterMap="HashMap">
  	select * from bookinfo where author=#author# and publish=#publish#
  	</select>
</sqlMap>  
Copy after login
写到这,是不是感到缺少什么文件啊,比如链接数据库的代码在哪,还有像hibernate还有一个总的配置文件啊,都在哪呢?现在就写数据库的链接代码!

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc\:mysql\://localhost\:3306/book?autoReconnect\=true&useUnicode\=true&characterEncoding\=utf8  
jdbc.username=root  
jdbc.password=root
Copy after login
总的配置文件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>
<!-- 引入JDBC的配置文件 -->
	<properties resource="jdbc.properties" />
	<transactionManager type="JDBC">
		<dataSource type="SIMPLE">
			<property name="JDBC.Driver" value="${jdbc.driverClassName}" />
			<property name="JDBC.ConnectionURL" value="${jdbc.url}" />
			<property name="JDBC.Username" value="${jdbc.username}" />
			<property name="JDBC.Password" value="${jdbc.password}" />
		</dataSource>
	</transactionManager>
	<!-- 引入各个类的实体映射文件 -->
	<sqlMap resource="com/wxc/bean/BookInfo.xml" />
</sqlMapConfig>  
Copy after login
到这里还没有什么感觉,还是把dao和impl写出来再说

BookInfogDao.java

package com.wxc.dao;

import java.util.List;

import com.wxc.bean.BookInfo;

public interface BookInfoDao {
	/**
	 * 获取所有图书信息
	 */
	public List<BookInfo> listBookInfo();
	
	/**
	 * 根据作者获取图书信息
	 */
	public List<BookInfo> bookInfoByAuthor(String name);
	
	/**
	 * 修改图书信息
	 */
	public void update(BookInfo bookinfo);
	
	/**
	 * 删除图书信息
	 */
	public void delete(int id);
	
	/**
	 * 注意这里的参数不是一个而是两个
	 * 根据作者与出版社获取图书信息
	 */
	public List<BookInfo> listByAuthorAndPublish(String author,String publish);
}	
Copy after login
BookInfoDaoImpl.java

package com.wxc.impl;

import java.io.Reader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.wxc.bean.BookInfo;
import com.wxc.dao.BookInfoDao;

public class BookInfoDaoImpl implements BookInfoDao {
	private static SqlMapClient sqlMapClient = null;
	
	//读取配置文件
	static{
		try {
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<BookInfo> listBookInfo() {
		List<BookInfo> list = null;
		try {
			//注意第一个参数,是对应xml文件里的查询id
			list = this.sqlMapClient.queryForList("listBookInfo", null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BookInfo> bookInfoByAuthor(String name) {
		List<BookInfo> list = null;
		try {
			list = this.sqlMapClient.queryForList("listBookInfoByAuthor", name);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@SuppressWarnings("static-access")
	@Override
	public void update(BookInfo bookinfo) {
	try {
		this.sqlMapClient.update("update", bookinfo);
	} catch (SQLException e) {
		e.printStackTrace();
	}
	}

	@SuppressWarnings("static-access")
	@Override
	public void delete(int id) {
		try {
			this.sqlMapClient.delete("delete", id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<BookInfo> listByAuthorAndPublish(String author, String publish) {
		Map mp = new HashMap();
		mp.put("anthor", author);
		mp.put("publish", publish);
		List<BookInfo> list = null;
		try {
			list = this.sqlMapClient.queryForList("listByAuthorAndPublis", mp);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

}
Copy after login
到此,所有的文件都敲好了,只需要写一个测试类调用Impl里的方法就行了。这里说几点ibatis独特的地方,注意实体类的映射文件BookInfo.xml里有

还有一点,SQL语句引用外部参数的写法是“#params#”,有时候会遇到传来的参数是一个或者是一个类,这样好处理,比如上面的update和delete,有的时候是多条件处理应该怎么办,比如上面的“listByAuthorAndPublis”,这里就需要用到Map了,在dao里(对了,调用xml的查询方法在dao里有queryforlist()和queryforobject()看你需要什么样的操作了,里面的参数queryforlist(arg0,arg1)分别对应的是xml里的id和参数,这一点不能写错)就要事先定义一个map,然后将两个参数put进去,然后xml会根据key获取参数的值,如上面Impl代码里的“listByAuthorAndPublish”方法,这也是我建议大家用的方法,之前看到有的是这样写

xml


然后在java文件里这样写

String sql = author+"and publish"+publish;

也就是把sql语句从中间劈开,这样有的时候也许是通用的,但是也有特殊的时候,我就是被这样的写法坑了一次,所以建议大家还是用Map传递参数

到这里,有没有感到ibatis是一个持久层的框架啊,如果把hibernate比作是自动冲锋枪的话那ibatis数据半自动冲锋枪。sql语句还是需要自己写的!!!

好了,以上就是我对ibatis的初步认识,在以后如果有学到新的更近一层的知识,我会更新的!





Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to complete the horror corridor mission in Goat Simulator 3 How to complete the horror corridor mission in Goat Simulator 3 Feb 25, 2024 pm 03:40 PM

The Terror Corridor is a mission in Goat Simulator 3. How can you complete this mission? Master the detailed clearance methods and corresponding processes, and be able to complete the corresponding challenges of this mission. The following will bring you Goat Simulator. 3 Horror Corridor Guide to learn related information. Goat Simulator 3 Terror Corridor Guide 1. First, players need to go to Silent Hill in the upper left corner of the map. 2. Here you can see a house with RESTSTOP written on the roof. Players need to operate the goat to enter this house. 3. After entering the room, we first go straight forward, and then turn right. There is a door at the end here, and we go in directly from here. 4. After entering, we also need to walk forward first and then turn right. When we reach the door here, the door will be closed. We need to turn back and find it.

How to pass the Imperial Tomb mission in Goat Simulator 3 How to pass the Imperial Tomb mission in Goat Simulator 3 Mar 11, 2024 pm 01:10 PM

Goat Simulator 3 is a game with classic simulation gameplay, allowing players to fully experience the fun of casual action simulation. The game also has many exciting special tasks. Among them, the Goat Simulator 3 Imperial Tomb task requires players to find the bell tower. Some players are not sure how to operate the three clocks at the same time. Here is the guide to the Tomb of the Tomb mission in Goat Simulator 3! The guide to the Tomb of the Tomb mission in Goat Simulator 3 is to ring the bells in order. Detailed step expansion 1. First, players need to open the map and go to Wuqiu Cemetery. 2. Then go up to the bell tower. There will be three bells inside. 3. Then, in order from largest to smallest, follow the familiarity of 222312312. 4. After completing the knocking, you can complete the mission and open the door to get the lightsaber.

How to do the rescue Steve mission in Goat Simulator 3 How to do the rescue Steve mission in Goat Simulator 3 Feb 25, 2024 pm 03:34 PM

Rescue Steve is a unique task in Goat Simulator 3. What exactly needs to be done to complete it? This task is relatively simple, but we need to be careful not to misunderstand the meaning. Here we will bring you the rescue of Steve in Goat Simulator 3 Task strategies can help you better complete related tasks. Goat Simulator 3 Rescue Steve Mission Strategy 1. First come to the hot spring in the lower right corner of the map. 2. After arriving at the hot spring, you can trigger the task of rescuing Steve. 3. Note that there is a man in the hot spring. Although his name is Steve, he is not the target of this mission. 4. Find a fish named Steve in this hot spring and bring it ashore to complete this task.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Where can I find Douyin fan group tasks? Will the Douyin fan club lose level? Where can I find Douyin fan group tasks? Will the Douyin fan club lose level? Mar 07, 2024 pm 05:25 PM

TikTok, as one of the most popular social media platforms at the moment, has attracted a large number of users to participate. On Douyin, there are many fan group tasks that users can complete to obtain certain rewards and benefits. So where can I find Douyin fan club tasks? 1. Where can I view Douyin fan club tasks? In order to find Douyin fan group tasks, you need to visit Douyin's personal homepage. On the homepage, you will see an option called "Fan Club." Click this option and you can browse the fan groups you have joined and related tasks. In the fan club task column, you will see various types of tasks, such as likes, comments, sharing, forwarding, etc. Each task has corresponding rewards and requirements. Generally speaking, after completing the task, you will receive a certain amount of gold coins or experience points.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

See all articles