上篇文章写了mybatis传统方式创建,这篇文章就说一下基于注解的创建
1.以上篇文章为基础,删除EmpDao.xml
2.修改mybatis的主配置文件 mybatis-config.xml
<mappers>
<mapper class="org.zhang.dao.EmpDao"/>
</mappers>
3.使用注解
public interface EmpDao {
public List<Emp> findAll();
@Select("select * from emp where empno=#{empno}")
public Emp selectEmpByNO(Integer empno) throws IOException;
}
4.主类
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过主配置文件创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 通过SqlSessionFactory 对象来打开一个session
SqlSession session = sqlSessionFactory.openSession();
// 通过sqlSession 使用动态代理 来实现Dao接口
EmpDao dao = session.getMapper(EmpDao.class);
// 执行sql
Emp emp = dao.selectEmpByNO(1001);
System.out.println(emp);
}
5.优化
<mapper namespace="org.zhang.mapper.IEmpMapper">
<select id="selectEmpByNo" resultType="org.zhang.pojo.Emp">
select * from emp where empno=#{empno}
</select>
<select id="findAll" resultType="org.zhang.pojo.Emp">
select * from emp;
</select>
</mapper>
public class EmpMapperImpl implements IEmpMapper {
@Override
public List<Emp> findAll() throws IOException {
String resource = "mybatis-config.xml";
// 获取输入流
InputStream in= Resources.getResourceAsStream(resource);
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql
List<Emp> emps = sqlSession.selectList("findAll");
return emps;
}
@Override
public Emp selectEmpByNo(Integer empno) throws IOException {
String resource = "mybatis-config.xml";
// 获取输入流
InputStream in= Resources.getResourceAsStream(resource);
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql
Emp emp = sqlSession.selectOne("selectEmpByNo",empno);
return emp;
}
}
6.提炼工具类
public class MybatisUtils {
static InputStream in;
static SqlSession sqlSession;
public static SqlSession getSession(){
String resource = "mybatis-config.xml";
// 获取输入流
try {
in= Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
// 获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 获取SqlSession
sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
public static void closeSession(){
if(sqlSession != null){
sqlSession.close();
}
}
}
7.将数据库的连接属性 写在db.properties配置文件中
jdbc.driver =com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zhang
jdbc.username=root
jdbc.password=123456