MyBatis是一个可以自定义SQL,存储过程和高级映射的持久层框架,MyBatis摒除了大部分的JDBC代码,手工设置
参数和结果集重获,MyBatis只是用简单的XML(Xtensible Markup Language)和注解来配置和映射基础数据
类型,Map接口和POJO到数据库记录.相对Hibernate和Apache OJB等"一站式"ORM解决方案而言,Mybatis是一种
半自动化的orm实现 object Relational Mapping;
Hibernate是全ORM映射框架,它只需要配置好文件,表会自动生成,
CURD的SQL语句也是自动生成的,这是他们的主要区别。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。
mybatis-spring-1.0.0.jar(与Spring结合包)。
下载地址:
http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/
MyBatis独立配置+maven 需要一些依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.ibatis</groupId>
<artifactId>ibatis_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!--log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--dom4j 解析xml -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--独立测试junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
配置SqlMapConfig.xml ,这里后期会交给spring管理spring事务处理
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--这里还可以用配置文件的方式来配置方面后期管理dp.properties-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapper/PersonTestMapper.xml"/>
</mappers>
</configuration>
配置文件的方式
dp.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
db.username =root
db.password =root
一定要声明<properties resource="db.properties"/>
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
创建实体类
User:
package cn.ibatis.pojo;
import java.io.Serializable;
/**
* 序列化可以转成对象去存储
*/
public class User implements Serializable{
private Integer uid;
private String username;
private String password;
public User() {
}
public User(Integer uid, String username, String password) {
this.uid = uid;
this.username = username;
this.password = password;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
创建dao:
UserDao:
package cn.ibatis.dao;
import cn.ibatis.pojo.User;
import java.util.List;
public interface UserDao {
public List<User> findAll();
}
创建UserMapper:
<?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="cn.ibatis.dao.UserDao">
<!-- select 查询
基于动态代理
约定:
namespace:dao接口的全限定类名
id:当前执行的方法名
-->
<select id="findAll" resultType="cn.ibatis.pojo.User">
select * from user
</select>
</mapper>
创建测试类:
MybatisTest:
package cn.ibatis.test;
import cn.ibatis.dao.UserDao;
import cn.ibatis.pojo.User;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void test() throws IOException {
//1.加载配置文件
// InputStream is = UserDaoTest.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
//通过mybatis提供的工具类加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
System.out.println(is);
//2.创建sqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.创建sqlSessionFactory
System.out.println(builder);
SqlSessionFactory sessionFactory = builder.build(is);
//4.创建sqlSession
SqlSession sqlSession = sessionFactory.openSession();
//5.创建dao的动态代理对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> list = userDao.findAll();
for (User user : list) {
System.out.println(user);
}
}
}
细节问题
这里需要配置好路径:
SqlMapConfig.xml里面
sql:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`uid` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL DEFAULT '',
`password` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`uid`)
) ENGINE=INNODB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', '123');
INSERT INTO `user` VALUES ('2', 'demo', '123');
INSERT INTO `user` VALUES ('3', 'iii', '454');
INSERT INTO `user` VALUES ('4', 'abc', '123');
INSERT INTO `user` VALUES ('20', 'ddd', '1241545');
INSERT INTO `user` VALUES ('21', 'dddd', '1241545');
运行成功:
有兴趣的小伙伴可以进群交流