简单Demo入门:
MyBatis 最开始是apache的一个开源项目iBatis, 2010年这个项目迁移到了google code名下,并且改名为MyBatis 。2013年11月迁移到Github。
现在开始入门
一:建一个项目并加入jar包
所需要的基础jar包:
mybatis需要jar包:mybatis-3.3.0.jar
mysql驱动jar包:mysql-connector-java-5.1.15.-bin.jar
日志记录jar包:log4j.jar
二:创建一个数据库并创建一个表
由于mybatis没有自动建表功能,so建表
三:配置mybatis.cfg.xml
<?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>
<!-- 引入外部配置文件 -->
<properties resource="mysql.properties"></properties>
<!-- 配置mybatis运行环境 -->
<environments default="environment">
<environment id="environment">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- POOLED 表示支持JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
</configuration>
这里还多写了一个mysql.properties文件,听说性能会厉害点。。。。。。。。。。。。。。。。
四:书写javabean对象
public class person implements Serializable {
private int id;
private String name;
private int age;
//get,set省略。。。。
}
五:书写方法的接口basedao及映射文件basedao.xml
提供简答的增删改查
public interface basedao {
//增加
public int add(person p);
//删除
public int delete(Serializable id);
//ById查询
public person findById(Serializable id);
//查询全部
public List<person> findAll();
}
映射文件 basedao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.basedao">
<!-- 查询的时候,需要自定义返回结果 -->
<resultMap type="beans.person" id="personMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>
<!--sql语句没有区分大小 -->
<insert id="add" >
INSERT INTO person(NAME,age)VALUES(#{name},#{age});
</insert>
<delete id="delete">
DELETE FROM person WHERE id=#{id};
</delete>
<select id="findAll" resultMap="personMap">
SELECT * FROM person
</select>
<select id="findById" resultMap="personMap">
select * from person where id=#{id}
</select>
</mapper>
写好之后需要在mybatis.cfg.xml中注册,添加一下,配置文件的位置
<mappers>
<mapper resource="dao/basedao.xml"/>
</mappers>
六:搞个测试类
public class test1 {
@Test
public void test() throws IOException{
//使用MyBatis提供的Resources类加载mybatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
//开启事务
SqlSession session = build.openSession();
basedao mapper = session.getMapper(basedao.class);
//添加数据
person p = new person(2, "好几十", 12);
mapper.add(p);
//根据id来进行查找
person person = mapper.findById(5);
//根据id来进行删除
mapper.delete(2);
//查询全部
List<person> list = mapper.findAll();
System.out.println(list);
//提交事务
session.commit();
System.out.println("success!!");
}
}
然后就.....everything is ok!!!