MyBatis 是一款持久层框架。半自动化的ORM框架。
持久化是将程序数据在持久状态和瞬时状态间转换的机制。通俗的讲,就是瞬时数据(比如内存中的数据,是不能永久保存的)持久化为持久数据(比如持久化至数据库中,能够长久保存)。
项目结构
所有jar包
数据库
create database dbtest;
CREATE TABLE `dbtest`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NULL,
`password` VARCHAR(20) NULL,
`age` INT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `dbtest`.`user` (`id`, `username`, `password`, `age`) VALUES ('1', '喜羊羊', '111111', '17');
INSERT INTO `dbtest`.`user` (`id`, `username`, `password`, `age`) VALUES ('2', '懒羊羊', '222222', '18');
INSERT INTO `dbtest`.`user` (`id`, `username`, `password`, `age`) VALUES ('3', '灰太狼', '333333', '25');
详细过程
略
创建mybatis的配置文件
mybatis-config.xml
<configuration>
<properties resource="database.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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/dao/UserMapper.xml"/>
mappers>
configuration>
数据库的配置文件
database.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/dbtest?serverTimezone=Asia/Shanghai
username=root
password=123456
根据自己的数据库进行配置
日志文件
log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms.dao=debug
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
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
######################################################################################
# DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error
根据数据库编写实体类
User.java
package com.pojo;
/**
* 用户类
* @author 12505
*
*/
public class User {
private int id;//id
private String username;//用户名
private String password;//用户密码
private int age;//用户年龄
//getter 和setter方法
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return " ID:"+this.id+
" 用户名:"+this.username+
" 密码:"+this.password+
" 年龄:"+this.age;
}
}
创建dao层的接口
UserMapper.java
package com.dao;
import java.util.List;
import com.pojo.User;
public interface UserMapper {
/**
* 查询所有用户信息
* @return 返回一个包含用户的列表
*/
public List<User> selectAllUser();
}
创建dao层接口的映射文件
UserMapper.xml
<mapper namespace="com.dao.UserMapper">
<select id="selectAllUser" resultType="com.pojo.User">
select * from user
select>
mapper>
这个配置文件的基本语义是:在命名空间
com.dao.UserMapper
中定义了一个名为selectAllUser
的映射语句。有了这个映射语句就可以使用全限定名
com.dao.UserMapper.selectAllUser
来调用这个映射语句:List<User> users1= sqlSession.selectOne("com.dao.UserMapper.selectAllUser");
你又可以通过下面的方法:
UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectAllUser();
第二种方法有很多优势,它不依赖于字符串字面值,会更安全一点。
创建测试类
UserTest.java
package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.dao.UserMapper;
import com.pojo.User;
import org.apache.log4j.Logger;
public class UserTest {
private Logger logger = Logger.getLogger(UserTest.class);
@Test
public void selectAllTest(){
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//①创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
//②创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory= factoryBuilder.build(inputStream);
//③创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//④创建Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行sql语句
List<User> users = mapper.selectAllUser();
//遍历所有用户
for(User user:users){
logger.debug(user);
}
}
}
通过该测试类可知,mybatis操作步骤如下:
改善
由于SqlSessionFactoryBuilder在项目中一般只使用一次(即通过它创建一个SqlSessionFactory),它的使命就结束了。并且SqlSession也是可以公用,只创建一个就可以了。因此, 可以将它们编写在一个工具类中, 如下:
MyBatisUtil.java
package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.dao.UserMapper;
import com.pojo.User;
import com.util.MyBatisUtil;
import org.apache.log4j.Logger;
public class UserTest {
private Logger logger = Logger.getLogger(UserTest.class);
@Test
public void selectAllTest(){
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//①创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
//②创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory= factoryBuilder.build(inputStream);
//③创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//④创建Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
sqlSession.close();
//执行sql语句
List<User> users = mapper.selectAllUser();
//遍历所有用户
for(User user:users){
logger.debug(user);
}
}
@Test
public void selectAllUsers(){
logger.info("===============");
SqlSession sqlSession = MyBatisUtil.createSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectAllUser();
sqlSession.commit();
MyBatisUtil.closeSqlSession(sqlSession);
for(User user:users){
logger.debug(user);
}
}
}
以后,需要创建SqlSession,直接调用这个类中的createSqlSession方法就可以了。