- mybatis 的前身是 ibatis.
ibatis 最早再Apache 下开源。
后来在google上开源,改名为Mybatis。现在在github上开源。
- MyBaits是一款一流的支持自定义SQL,存储过程和高级映射的持久化框架。
- MyBaitis 是一个半自动化的orm框架。
- 开发步骤如下:
- 新建java项目
- 导入jar包:
mybatis-3.2.7.jar mysql-connector-java-5.1.20-bin.jar
- 编写mubatis配置文件:
<?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"> <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="1111" /> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/wh/mapper/RoleMapper.xml" /> </mappers> </configuration>
- 编写Mybatis 工具类:
/** * Mybatis的工具类 */ public class MybatisUtil { private static SqlSessionFactory sessionFactory=null; private static ThreadLocal<SqlSession> session = new ThreadLocal<SqlSession>(); static{ try { Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** * 获取SQLSession * @return */ public static SqlSession getSqlSession(){ if(session.get()==null){ session.set(sessionFactory.openSession()); } return session.get(); } /** * 释放资源 */ public static void close(){ if(session.get()!=null){ session.get().close(); session.set(null); } } }
- 编写映射文件:
<?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.sxt.mapper.RoleMapper"> <select id="findById" parameterType="int" resultType="cn.wh.vo.Role"> select * from t_role where id = #{id} </select> </mapper>
- 测试:
public class Demo { public static void main(String[] args) { SqlSession session = MybatisUtil.getSqlSession(); Role role = (Role)session.selectOne("cn.wh.mapper.RoleMapper.findById", 1); System.out.println(role.getId()+"----"+role.getName()); MybatisUtil.close(); } }