1.先导入包到项目lib文件夹中;
2.在src根目录文件中建立:SqlMapConfig.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>
<typeAliases>
<typeAlias type="cn.com.leadfar.cms.backend.model.Admin" alias="Admin"/>
<typeAlias type="cn.com.leadfar.cms.backend.model.Article" alias="Article"/>
</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/wuyanwen" />
<property name="username" value="wuyanwen" />
<property name="password" value="wuyanwen" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/com/leadfar/cms/backend/dao/impl/Admin.xml" />
<mapper resource="cn/com/leadfar/cms/backend/dao/impl/Article.xml" />
</mappers>
</configuration>
3.编写映射文件:
Admin.xml文件
<?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.com.leadfar.cms.backend.model.Admin">
<insert id="add" parameterType="Admin">
insert into t_admin (username,password) values (#{username},#{password})
</insert>
<select id="findAdminByUsername" parameterType="string" resultType="Admin">
select * from t_admin where username = #{username}
</select>
</mapper>
4.利用ibatisAPI文档直接拿来使用:
package cn.com.leadfar.cms.backend.dao.impl;
import org.apache.ibatis.session.SqlSession;
import cn.com.leadfar.cms.backend.dao.AdminDao;
import cn.com.leadfar.cms.backend.model.Admin;
import cn.com.leadfar.cms.utils.MyBatisUtil;
public class AdminDaoForMyBatisImpl extends BaseDao implements AdminDao {
public void addAdmin(Admin admin) {
add(admin);
}
public Admin findAdminByUsername(String username) {
//打开一个session
SqlSession session = MyBatisUtil.getSession();
Admin admin = null;
try {
admin = (Admin)session.selectOne(Admin.class.getName()+".findAdminByUsername", username);
} catch (Exception e) {
e.printStackTrace();
} finally{
//关闭session
session.close();
}
return admin;
}
}
5.leadfar.cms.utils
package cn.com.leadfar.cms.utils;
import java.io.IOException;
import java.io.Reader;
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 {
static SqlSessionFactory factory = null;
static{
try {
//通过配置文件,创建工厂对象
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static SqlSession getSession(){
return factory.openSession();
}
}