mybatis是一款很好的ORM框架,但不是纯粹的面向对象的操作,不如称之为“SQL Mapping”框架。下面我们以一个小demo来介绍它的使用
1、首先看一下我的目录
2、加入mybatis和db2连接的jar包(前两个是db2的jar包,后面一个是mybatis的jar包)
3、实体类、实现方法和对应的xml文件
User.java(实体类)
package com.iflysse.bbs.model;
public class User {
private int id;
private String name;
private String account;
private String email;
private String password;
//get、set方法省略
}
UserDao.java(实现类)
package com.iflysse.bbs.dao;
import java.util.List;
import com.iflysse.bbs.model.User;
public interface UserDao {
public void insert(User user);
public void update(User user);
public void delete(int userId);
public User getUser(int userId);
public List<User> getUserList(String name);
}
<?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">
<!--等价于dao接口的实现 namespace必须和接口的类路径一样 -->
<mapper namespace="com.iflysse.bbs.dao.UserDao">
<resultMap type="User" id="UserResultMap">
<id property="id" column="id" />
<result property="account" column="account" />
<result property="name" column="name" />
<result property="email" column="email" />
<result property="password" column="password" />
</resultMap>
<insert id="insert" parameterType="User">
<![CDATA[
INSERT INTO user(name,account,email,password) VALUES(#{name},#{account},#{email},#{password})
]]>
</insert>
<update id="update" parameterType="User">
<![CDATA[
UPDATE user SET name=#{name},account=#{account},email=#{email},password=#{password} WHERE id=#{id}
]]>
</update>
<delete id="delete" parameterType="int">
<![CDATA[
DELETE FROM user WHERE id=#{userId}
]]>
</delete>
<select id="getUser" parameterType="int" resultMap="UserResultMap">
<![CDATA[
SELECT * FROM user WHERE id=#{userId}
]]>
</select>
<select id="getUserList" parameterType="String" resultMap="UserResultMap">
<![CDATA[
SELECT * FROM user WHERE name like #{name}
]]>
</select>
</mapper>
package com.iflysse.bbs.test;
import java.io.IOException;
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 com.iflysse.bbs.dao.UserDao;
public class Test {
public static void main(String[] args) throws IOException {
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
SqlSession session = sessionFactory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
System.out.println(userDao.getUser(2).getName());
session.commit();
}
}
测试结果
小结:MyBatis框架是一个面向SQL的框架,使用起来很方便,让我们一起学习吧