第一步加载相应的jar包。
第二步:编写输出日志文件:log4j.properties(可选项)
#Configure logging for testing: optionally with log file
log4j.rootLogger=DEBUG, stdout
# log4j.rootLogger=WARN, stdout,logfile,\u5982\u679C\u662F\u751F\u4EA7\u73AF\u5883\u5C31\u662FINFO,ERROR
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d%p [%c] - %m%n
第三步:编写jdbc的配置文件(针对数据库的一些配置。)mybatis-config.xml配置文件:
PUBLIC "-//mybatis.org//DTD Config3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
第四步:编写PreparedStatement处理的sql文本。这个文本是写在配置文件里,比如我针对cate这张表的操作,那么会创建一个catemapper.xml的配置文件,文件格式如下:
PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
Select * From cate Where id=#{id}
第五步:需要将该sql配置文件加入到基础配置文件里(mybatis-config.xml文件里)
第六步,Mybatis的操作程序。
操作示范代码:
InputStream inputStream =Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
//产生一个SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
Cate cate =sqlSession.selectOne("test.selectCateOne", 2048);//找相应的sql语句就需要通过命名空间的方式去操作
System.out.println("分类名称:"+cate.getName());
sqlSession.close();