简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
发展
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
使用
虽然有很多插件可以一键生成代码 但是还是觉得应该记录一下手写的过程
1.导入依赖包
mybtis相关
mybatis-3.2.8.jar
slf4j-api-1.7.5.jar
asm-3.3.1.jar
log4j-api-2.0.2.jar
log4j-core-2.0.2.jar
slf4j-log4j12-1.7.5.jar
cglib-2.2.2.jar
log4j-1.2.17.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
jbdc
mysql-connector-java-5.1.30-bin.jar
2.编写mybits核心配置文件(一般在src目录下创建xml文件)
mybatis-conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd">
<configuration>
<environments default="environments">
<environment id="sky"> <!-- test读取配置文件时要加载哪个配置 -->
<transactionManager type="JDBC"></transactionManager><!-- 使用jdbc的事务管理 -->
<dataSource type="POOLED"><!-- 使用连接池 -->
<!-- <property name="" value=""/> -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers >
<!-- 功能映射文件的位置 (增删改查) -->
<mapper resource="com/lin/dao/UserMapper.xml"/>
</mappers>
</configuration>
3.编写javaBean(entity)
Users
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
private int userid;
private String username;
private String password;
private String sex;
public Users() {
}
public Users(String username, String password, String sex) {
this.username = username;
this.password = password;
this.sex = sex;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Users{" +
"userid=" + userid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", sex=" + sex +
'}';
}
}
4.编写dao层接口
UserDao
public interface UserDao {
public int add(Users users);
public int remove(Users user);
public int update(Users user);
public List<Users> queryAllUser();
}
5.将接口的实现类转换为Mapper.xml的配置文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<!--<mapper namespace="com.lin.entity"><!– 名空间 ==唯一的–>-->
<mapper namespace="com.lin.dao.UserDao"><!-- 名空间 ==使用接口时==标记当前配置文件为接口的实现类-->
<!-- 要对哪个类进行类型转换 === user.setUsername(rs.getString(2))-->
<resultMap type="com.lin.entity.Users" id="BaseResultMap">
<!-- <id column="数据库中列名" property="javabean中的属性名" jdbcType="数据库中的类型"/> -->
<id column="userid" property="userid" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="sex" property="sex" jdbcType="VARCHAR"/>
</resultMap>
<!-- insert id="名字" parameterType="全包类路径名称" useGeneratedKeys="true"==使用jdbc的自增长机制 keyProperty="主键自增长的列名叫什么" -->
<!-- 配置文件的方法id要与接口中方法名相对应-->
<insert id="add" parameterType="com.lin.entity.Users" useGeneratedKeys="true" keyProperty="userid">
insert into user (username,password,sex) values(#{username},#{password},#{sex})
</insert>
<delete id="remove" parameterType="com.lin.entity.Users">
delete from user where username=#{username}
</delete>
<update id="update" parameterType="com.lin.entity.Users">
update user set password=#{password} where username=#{username}
</update>
<select id="queryAllUser" resultMap="BaseResultMap" >
select * from user
</select>
<select id="login" parameterType="com.lin.entity.Users" resultMap="BaseResultMap">
select * from user where username=#{username} and password=#{password}
</select>
</mapper>
6.封装SessionFactory
SessionFactory
public class SessionFactory {
SqlSessionFactory sqlSessionFactory = null;
public SessionFactory() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// test---主配置文件中的名称为test的环境---oracle---test2l
sqlSessionFactory = builder.build(reader, "sky");
}
public SqlSession getSession(){
return sqlSessionFactory.openSession();
}
// 通过此方法获得dao的映射
public <T> T getMapper(Class mapper){
return (T) getSession().getMapper(mapper);
}
}
7.测试类
Test
public class Test {
public static void main(String[] args) throws IOException {
SessionFactory sessionFactory = new SessionFactory();
SqlSession session = sessionFactory.getSession();
UserDao userDao = session.getMapper(UserDao.class);
Users user = new Users();
user.setUsername("777");
user.setPassword("555");
user.setSex("女");
// //添加
// userDao.add(user);
// //删除
// userDao.remove(user);
// //修改
// userDao.update(user);
//查询
List<Users> usersList = userDao.queryAllUser();
for (Users theuser:usersList) {
System.out.println(theuser);
}
session.commit();
session.close();
}
}