一、Mybatis介绍
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
jdbc/dbutils/springdao,hibernate/springorm,mybaits同属于ORM解决方案之一.
二、Mybatis快速入门
1)创建一个javaweb工程,然后导入mybatis和mysql的jar包
或者使用maven创建项目,然后在pom.xml文件中添加下面的依赖
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
2)创建实体类对象(文件项目路径:com.madman0621.entity.User.java)
package com.madman0621.entity;
public class User {
private int id;
private String username;
private String password;
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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User() {
super();
}
}
3)在实体类同级目录下创建UserMapper.xml配置文件
<mapper namespace="mynamespace">
<resultMap type="user" id="UserMap">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
resultMap>
<insert id="addUser1">
insert into user(id,username,password) values(21,'mybatis','mybatis')
insert>
<insert id="addUser2" parameterType="user">
insert into user(username,password) values(#{username},#{password})
insert>
mapper>
4)在sr目录下创建mybatis.xml配置文件
<configuration>
<typeAliases>
<typeAlias type="com.madman0621.entity.User" alias="user"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<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/madman0621/entity/UserMapper.xml"/>
mappers>
configuration>
5)在util目录下创建MyBatisUtil.java类,并测试与数据库是否连接
package com.madman0621.util;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
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 MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
private static SqlSession sqlSession;
//加载位于src/mybatis.xml配置文件
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
//禁止外界通过new方法创建
private MyBatisUtil() {}
//获取SqlSession
public static SqlSession getSqlSession() {
sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
//连接测试
public static void main(String[] args) {
Connection conn = MyBatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?"连接成功":"连接失败");
}
}
6)在java代码中实现添加用户
方法一:
在dao目录创建UserDao类并进行测试
package com.madman0621.dao;
import org.apache.ibatis.session.SqlSession;
import com.madman0621.entity.User;
import com.madman0621.util.MyBatisUtil;
public class UserDao {
//增加学生(无参)
public void addUser1() {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
//事务开始(默认)
//读取StudentMapper.xml映射文件中的SQL语句
//调用方法:名称空间.sql语句的id
sqlSession.insert("mynamespace.addUser1");
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
//增加学生(带参)
public void addUser2(User user) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
//事务开始(默认)
//读取StudentMapper.xml映射文件中的SQL语句
//调用方法:名称空间.sql语句的id
sqlSession.insert("mynamespace.addUser2",user);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
//测试方法
public static void main(String[] args) {
UserDao userDao = new UserDao();
//无参方式添加
userDao.addUser1();
//带参方式添加
User user = new User("test","test");
userDao.addUser2(user);
}
}
方法二:
1、在dao目录下创建UserDao.java接口类对象
package com.madman0621.dao;
import com.madman0621.entity.User;
public interface UserDao {
public void addUser1();
public void addUser2(User user);
}
2、将UserMapper.xml的名称空间修改为UserDao接口类对象的全路径
<mapper namespace="com.madman0621.dao.UserDao">
。。。
mapper>
3、创建测试类测试UserDao的方法
package com.madman0621.test;
import org.apache.ibatis.session.SqlSession;
import com.madman0621.dao.UserDao;
import com.madman0621.entity.User;
import com.madman0621.util.MyBatisUtil;
public class UserTestByMapper {
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
//获取UserDao接口对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
//无参添加用户
userDao.addUser1();
//带参添加用户
User user = new User("mapper","mapper");
userDao.addUser2(user);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
}
方法二解析:
UserDao.java是XML 映射配置文件UserMapper.xml 里命名空间指向的接口:
< mapper namespace="com.madman0621.dao.UserDao">
一般来说,一个XML 映射配置文件对应一个命名空间,而这个命名空间又对应一个接口,这样我们就可以定义这样一个接口,并类型安全地执行SQL 语句,如:
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.addUser1();
MyBatis 启动时首先会根据XML 配置文件中的命名空间查找是否存在这个接口类,如果存在则保存在一个名为knownMappers 的HashSet 中。