从同事那知道有个轻量级的持久化工具,简单入手,适合中小型项目,所以充充电,简单了解下它的基本使用。
下面是自己的学习例子——图书的添删改查:
项目文档结构如下:
1、新建项目,导入Mybatis 需要的jar 包,以及数据库的驱动包:
这里我使用的是Mybatis 版本是 mybatis-3.0.5 ;数据库使用的是oracle 数据库。
所以导入相应的包:mybatis-3.0.5.jar 、ojdbc14.jar
2、建立图书 javabean —— Book.java :
package com.mybatis.Bean;
public class Book {
private int bid;
private String bookName;
private String price;
private String author;
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
当然,相应的我们应该在数据库中建立对应的表book—— book.sql
create table book(
bid int not null,
bookName varchar(20),
price varchar(10),
author varchar(10)
)
3、开始配置 Mybatis
mybatis 总配置文件 —— sqlMapConfig.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="com/mybatis/util/jdbc.properties"></properties>
<typeAliases>
<typeAlias type="com.mybatis.Bean.Book" alias="Book" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/Mapper/BookMapper.xml" />
</mappers>
</configuration>
mybatis 数据库参数配置文件 —— jdbc.properties:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=hollydm
password=hollydm
创建MyBatis映射文件 ——BookMapper.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatisWeb.Book">
<sql id="bookColumns">bid,bookName,price,author</sql>
<!-- 查询结果集为实体Book -->
<select id="getBookById" parameterType="int" resultType="Book">
select
<include refid="bookColumns" />
from book where bid = #{id}
</select>
<!-- 查询结果集为实体Book -->
<select id="getBookList" resultType="Book">
select
<include refid="bookColumns" />
from book
</select>
<!-- 查询结果集为实体Book -->
<select id="getBook" parameterType="Book" resultType="Book">
select
<include refid="bookColumns" />
from book where author='lala'
<!--
<if test='author != null || "".equals(author)'>
where author =#{author}
</if>
-->
<choose>
<when test="price != null ">AND price like #{price}</when>
<when test="name != null ">AND bookName like #{name}</when>
</choose>
</select>
<!-- 新增 -->
<insert id="insertBook" parameterType="Book">
insert into book(
<include refid="bookColumns" />
) values(#{bid},#{bookName},#{price},#{author})
</insert>
<!-- 修改 -->
<update id="updateBook" parameterType="Book">
update book set
bookName=#{bookName},price=#{price},author=#{author} where
bid=#{bid}
</update>
<!-- 删除 -->
<delete id="deleteBook" parameterType="int">
delete from book where bid =#{id}
</delete>
</mapper>
4、创建一个工具类 ——MyBatisUtil.java :
package com.mybatis.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private static final String RESOURCE = "com/mybatis/util/sqlMapConfig.xml";
public static SqlSessionFactory getSqlSessionFactory() {
try {
Reader reader = Resources.getResourceAsReader(RESOURCE);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder()
.build(reader);
return sqlMapper;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
5、生成对图书添删改查操作的接口类——IBookDao.java :
package com.mybatis.Dao;
import java.util.List;
import com.mybatis.Bean.Book;
public interface IBookDao {
public Book getBookById(int bid);
public List<Book> getAllBook();
public void addBook(Book book);
public void delBook(int bid);
public void updateBook(Book book);
public List<Book> getBook(Book book);
}
6、生成对图书操作的接口实现类 ——IbookDaoImp.java:
package com.mybatis.Dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.mybatis.Bean.Book;
import com.mybatis.util.MyBatisUtil;
public class IbookDaoImp implements IBookDao {
private static SqlSessionFactory sessionFactory;
static {
sessionFactory = MyBatisUtil.getSqlSessionFactory();
}
public void addBook(Book book) {
SqlSession session = sessionFactory.openSession();
try {
session.insert("com.mybatisWeb.Book.insertBook", book);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public void delBook(int bid) {
SqlSession session = sessionFactory.openSession();
try {
int count = session.delete("com.mybatisWeb.Book.deleteBook", bid);
session.commit();
System.out.println(count);
} finally {
session.close();
}
}
public List<Book> getAllBook() {
SqlSession session = sessionFactory.openSession();
List<Book> bookList = new ArrayList<Book>();
try {
bookList = session.selectList("getBookList");
} finally {
session.close();
}
return bookList;
}
public Book getBookById(int bid) {
SqlSession session = sessionFactory.openSession();
Book book = new Book();
try {
book = (Book) session.selectOne("com.mybatisWeb.Book.getBookById",
bid);
} finally {
session.close();
}
return book;
}
public List<Book> getBook(Book book) {
SqlSession session = sessionFactory.openSession();
List<Book> bookList = new ArrayList<Book>();
try {
bookList = session.selectList("com.mybatisWeb.Book.getBook",
book);
} finally {
session.close();
}
return bookList;
}
public void updateBook(Book book) {
SqlSession session = sessionFactory.openSession();
try {
session.update("com.mybatisWeb.Book.updateBook", book);
session.commit();
} finally {
session.close();
}
}
}
7.主函数测试类——BookTestMain.java:
package com.mybatis.Test;
import java.util.ArrayList;
import java.util.List;
import com.mybatis.Bean.Book;
import com.mybatis.Dao.IBookDao;
import com.mybatis.Dao.IbookDaoImp;
public class BookTestMain {
public static void main(String[] a) {
try {
IBookDao ibookDao = new IbookDaoImp();
// 1、增加
// Book book = new Book();
// book.setBid(3);
// book.setBookName("ibatis");
// book.setPrice("99");
// book.setAuthor("kailai");
// ibookDao.addBook(book);
// 2、获取一本图书
// Book book = new Book();
// book = ibookDao.getBookById(1);
// System.out.print("name :" + book.getBookName());
// 3、获取所有图书
// List<Book> blist = new ArrayList<Book>();
// blist = ibookDao.getAllBook();
// for (int i = 0; i < blist.size(); i++) {
// System.out.println("bid : " + blist.get(i).getBid()
// + " \nname: " + blist.get(i).getBookName()
// + " \nprice: " + blist.get(i).getPrice() + "\nAuthor:"
// + blist.get(i).getAuthor() + "\n");
// }
// 4、删除图书
// ibookDao.delBook(3);
// 5、更新图书
// Book book = new Book();
// book.setBid(2);
// book.setBookName("ibatis");
// book.setPrice("98");
// book.setAuthor("lala");
// ibookDao.updateBook(book);
// book = ibookDao.getBookById(1);
// System.out.println("bid : " + book.getBid() + " \nname: "
// + book.getBookName() + " \nprice: " + book.getPrice());
// 6、获取一本图书
Book book = new Book();
book.setAuthor(null);
book.setPrice("99");
List<Book> blist = new ArrayList<Book>();
blist = ibookDao.getBook(book);
System.out.println("总共有 " + blist.size() + " 本书!");
for (int i = 0; i < blist.size(); i++) {
System.out.println("bid : " + blist.get(i).getBid()
+ " \nname: " + blist.get(i).getBookName()
+ " \nprice: " + blist.get(i).getPrice() + "\nAuthor:"
+ blist.get(i).getAuthor() + "\n");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}