1.第一步:創建java工程
使用eclipse創建java工程,jdk使用1.7.0_72。
2.第二步:加入jar包
加入mybatis核心包、依賴包、數據驅動包。
3. 第三步:log4j.properties(mybatis默認使用log4j作爲輸出日誌信息。)
配置如下:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4.第四步:mybatis核心配置文件 SqlMapConfig.xml(必須在classpath下)
<?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>
<!-- 和spring整合後 environments配置將廢除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事務管理-->
<transactionManager type="JDBC" />
<!-- 數據庫連接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlMapper.xml"/>
</mappers>
</configuration>
5.第五步:po類
po類通常與數據庫表對應(這裏使用用戶實體類User.java)
6.第六步:sql映射文件(在classpath下建立sqlMapper.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="test">
<!-- 根據id獲取用戶信息 -->
<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
select * from user where id = #{id}
</select>
</mapper>
7.第七步:測試程序
public class Mybatis_first {
//會話工廠
private SqlSessionFactory sqlSessionFactory;
@Before
public void createSqlSessionFactory() throws IOException {
// 配置文件
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);}
// 根據 id查詢用戶信息
@Test
public void testFindUserById() {
// 數據庫會話實例
SqlSession sqlSession = null;
try {
// 創建數據庫會話實例sqlSession
sqlSession = sqlSessionFactory.openSession();
// 查詢單個記錄,根據用戶id查詢用戶信息
User user = sqlSession.selectOne("test.findUserById", 10);
// 輸出用戶信息
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();}}}}