<?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">
<!-- 一般在查询时使用-->
<!-- 定义插入的sql语句,通过命名空间+id方式被定位 -->
insert into dept(dept_name,dept_address) values(#{deptName},#{deptAddress})
<update id="update" parameterType="Dept">
update dept set dept_name=#{deptName},dept_address=#{deptAddress}
where dept_id =#{deptId}
</update>
<delete id="delete" parameterType="Dept">
delete from dept where dept_id=#{deptId}
</delete>
<select id="selectOne" parameterType="int" resultMap="deptResultMap" >
select * from dept where dept_id=#{deptId}
</select>
<select id="selectList" parameterType="string" resultMap="deptResultMap">
select * from dept where dept_address=#{deptAddress}
</select>
public class MyBatisUtil {
private static final ThreadLocal threadLocal = new ThreadLocal();
private static SqlSessionFactory sessionFactory;
private static String CONFIG_FILE_LOCATION ="myBatis-config.xml";
static {
try {
buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private MyBatisUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws Exception
*/
public static SqlSession getSession() throws Exception {
SqlSession session = (SqlSession) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
buildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* build session factory
*
*/
public static void buildSessionFactory() {
Reader reader=null;
try {
reader=Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Close the single session instance.
*
*/
public static void closeSession(){
SqlSession session = (SqlSession) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
}
public Dept selectOne(int deptId) {
Dept dept = null;
SqlSession session = null;
try {
session = MyBatisUtil.getSession();
dept = (Dept)session.selectOne("cn.scau.cty.DeptMapper.selectOne", deptId);
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally{
MyBatisUtil.closeSession();
}
return dept;
}
@Test
public void testSelectOne(){
Dept dept = deptDaoImpl.selectOne(4);
System.out.println("查询到的记录部门是"+dept);
}
查询到的记录 是null 求大神帮忙看下 谢谢了
上面没显示出来的是这个
deptResultMap你这个有定义么?有没有对应好。