1.用eclipse创建动态web项目,命名为mybatis
2.右键mybatis项目,选择Build Path, Configure Build Path…
3.导入相关的jar包,点击Add External JARS, 把这三个jar包导入后,最后点击Apply。需导入的jar包如下:
log4j-1.2.17.jar;
mybatis-3.4.1.jar;
mysql-connector-java-6.0.6.jar
另外原项目与jar包我已保存到了网盘,方便下载与学习:
https://pan.baidu.com/s/1WRysIDE-DcbyQA-Jogu2lQ 密码: xjkc
(1)Book.java
构建一个POJO对象:
package com.edu.mybatis.pojo;
public class Book {
int id;
String bookName;
String author;
float price;
String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
(2)BookMapper.java
采用XML方式构建映射器,它包含一个接口和一个XML。
package com.edu.mybatis.mapper;
import java.util.List;
import com.edu.mybatis.pojo.Book;
public interface BookMapper {
public int insertBook(Book book); //新增
public int deleteBook(int id); //删除
public int updateBook(Book book); //更改
public Book getBook(int id); //获取书籍信息
public List findBooks(String bookName);//同名书籍列表
}
(3)BookMapper.xml
"1.0" encoding="UTF-8"?>
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org//dtd/mybatis-3-mapper.dtd">
namespace="com.edu.mybatis.mapper.BookMapper">
"insertBook" parameterType="book">
insert into t_book(book_id, book_name, book_author, book_price, book_description) values(#{id}, #{bookName}, #{author}, #{price}, #{description})
"deleteBook" parameterType="int">
delete from t_book where book_id= #{id}
"updateBook" parameterType="book">
update t_book set book_name = #{bookName}, book_author = #{author}, book_price = #{price}, book_description = #{description} where book_id= #{id}
<select id="getBook" parameterType="int" resultType="book">
select book_id as id, book_name as name, book_author as author, book_price as price, book_description as description from t_book where book_id= #{id}
select>
<select id="findBooks" parameterType="string" resultType="book">
select book_id as id, book_name as bookName, book_author as author, book_price as price, book_description as description from t_book where book_name like concat('%', #{bookName}, '%')
select>
XML文件里面的元素id标识了对应的SQL,parameterType标出了是什么类型的参数,resultType则代表结果映射为什么类型。其中insert、delete和update返回的是影响条数。
(4)SqlSessionFactoryUtils.java
通过SqlSessionFactoryBuilder来构建SqlSessionFactory,由于SqlSessionFactory应该采用单例模式,所以使用单例模式构建它。
package com.edu.mybatis.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryUtils {
private final static Class LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtils() {}
public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
public static SqlSession openSqlSession() {
if(sqlSessionFactory == null) {
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
构造方法中加入了private关键字,使得其他代码不能通过new的方式来创建它。而加入synchronized关键字加锁,主要是为了防止在多线程中多次实例化SqlSessionFactory对象,从而保证SqlSessionFactory的唯一性。而openSqlSession方法的作用则是创建SqlSession对象
(5)mybatis-config.xml配置文件
<configuration>
<typeAliases>
<typeAlias alias="book" type="com.edu.mybatis.pojo.Book"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/edu/mybatis/mapper/BookMapper.xml"/>
mappers>
configuration>
(6)log4j.properties日志文件配置
log4j.rootLogger=debug,stdout,logfile
### \u628A\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
### \u628A\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u6587\u4EF6\uFF1Ajbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
###\u663E\u793ASQL\u8BED\u53E5\u90E8\u5206
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
(7)Main.java
编写运行代码Main,如下:
package com.edu.mybatis.main;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import com.edu.mybatis.mapper.BookMapper;
import com.edu.mybatis.utils.SqlSessionFactoryUtils;
import com.edu.mybatis.pojo.Book;
public class Main {
public static void main(String[] args) {
Logger log = Logger.getLogger(Main.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSqlSession();
BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
//新增
// Book book = new Book();
// book.setId(6);
// book.setBookName("荷塘月色");
// book.setAuthor("zhu");
// book.setPrice(33.32f);
// book.setDescription("I like the moon.");
// bookMapper.insertBook(book);
//删除
//int book = bookMapper.deleteBook(6);
//修改
// Book book = bookMapper.getBook(6);
// book.setBookName("青春飞扬");
// book.setAuthor("帅哥");
// book.setPrice(66.35f);
// book.setDescription("青春不流逝");
// bookMapper.updateBook(book);
//查询所有同名书籍
List bookList = bookMapper.findBooks("cool");
for(Book book:bookList) {
log.info(book.getBookName());
log.info(book.getAuthor());
log.info(book.getPrice());
log.info(book.getDescription());
}
sqlSession.commit(); //注意增删改,需要commit,否则无效
//System.out.println(book.getAuthor());
//log.info(book.getAuthor());
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}
}
通过SqlSession获取了一个RoleMapper接口对象,然后通过findBooks方法获取对象,最后正确关闭SqlSession对象。
(8)使用MySQL数据库,需要自行安装
建立t_book表:
t_book表内容(自定义):
6.以Java Application的形式运行Main.java, 控制台打印日志如下:
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 900008524.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@35a50a4c]
DEBUG - ==> Preparing: select book_id as id, book_name as bookName, book_author as author, book_price as price, book_description as description from t_book where book_name like concat('%', ?, '%')
DEBUG - ==> Parameters: cool(String)
DEBUG - <== Total: 2
INFO - cool
INFO - wfe
INFO - 43.0
INFO - few
INFO - cool
INFO - haha
INFO - 66.0
INFO - hhh
DEBUG - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@35a50a4c]
DEBUG - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@35a50a4c]
DEBUG - Returned connection 900008524 to pool.
通过log4j.properties文件配置,让MyBatis打印其运行过程的轨迹。可以清晰地看到日志打印出来的SQL,SQL参数,以及返回的结果数。这样有利于监控MyBatis的运行过程和定位问题的所在。