首页 > 代码库 > 初识MyBatis

初识MyBatis

src/dao/student/StudentMapper.java        (绑定映射语句的接口,也称为映射器)

技术分享
 1 package dao.student; 2  3 /** 4  * 学生持久层接口 5  * @author Administrator 6  */ 7 public interface StudentMapper { 8     /** 9      * 获得学生总数10      */11     public int getStudentCount();12 }
View Code

src/dao/student/StudentMapper.xml         (sql映射文件,映射sql语句)

技术分享
1 <?xml version="1.0" encoding="UTF-8" ?>2 <!DOCTYPE mapper3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">5 <mapper namespace="dao.student.StudentMapper">6     <select id="getStudentCount" resultType="int">7         select count(1) from student8     </select>9 </mapper>
View Code

resources/database.properties                  (数据库连接配置文件)

技术分享
1 driver=com.mysql.jdbc.Driver2 url=jdbc:mysql://localhost:3306/mysqldemo?useUnicode=true&characterEncoding=utf-8&useSSL=true3 user=root4 password=root
View Code

resources/log4j.properties                         (log4j配置文件)

技术分享
 1 log4j.rootLogger=DEBUG,CONSOLE,file 2 #log4j.rootLogger=ERROR,ROLLING_FILE 3 log4j.logger.cn.smbms.dao=debug 4 log4j.logger.com.ibatis=debug  5 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug  6 log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug  7 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug  8 log4j.logger.java.sql.Connection=debug  9 log4j.logger.java.sql.Statement=debug 10 log4j.logger.java.sql.PreparedStatement=debug 11 log4j.logger.java.sql.ResultSet=debug 12 log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug13 14 ######################################################################################15 # Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e16 ######################################################################################17 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender18 log4j.appender.Threshold=error19 log4j.appender.CONSOLE.Target=System.out20 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout21 log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n22 23 24 ######################################################################################25 # DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-1126 ######################################################################################27 log4j.appender.file=org.apache.log4j.DailyRollingFileAppender28 log4j.appender.file.DatePattern=yyyy-MM-dd29 log4j.appender.file.File=log.log30 log4j.appender.file.Append=true31 log4j.appender.file.Threshold=error32 log4j.appender.file.layout=org.apache.log4j.PatternLayout33 log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n34 35 36 log4j.logger.com.opensymphony.xwork2=error  
View Code

resources/mybatis-config.xml                   (mybatis核心配置文件)

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5  6 <!-- 通过这个配置文件完成mybatis与数据库的连接 --> 7 <configuration> 8     <!-- 引入 database.properties 文件--> 9     <properties resource="database.properties"/>10     <!-- 配置mybatis的log实现为LOG4J -->11     <settings>12         <setting name="logImpl" value="LOG4J" />13     </settings>14     <environments default="development">15         <environment id="development">16             <!--配置事务管理,采用JDBC的事务管理  -->17             <transactionManager type="JDBC"></transactionManager>18             <!-- POOLED:mybatis自带的数据源,JNDI:基于tomcat的数据源 -->19             <dataSource type="POOLED">20                 <property name="driver" value="${driver}"/>21                 <property name="url" value="${url}"/>22                 <property name="username" value="${user}"/>23                 <property name="password" value="${password}"/>24             </dataSource>25         </environment>26     </environments>27     <!-- 将mapper文件加入到配置文件中 -->28     <mappers>29         <mapper resource="dao/student/StudentMapper.xml"/>30     </mappers>31 </configuration>
View Code

test/dao/student/StudentMapperTest.java(测试类)

技术分享
 1 package dao.student; 2  3 import org.apache.ibatis.session.SqlSession; 4 import org.apache.log4j.Logger; 5 import org.junit.Before; 6 import org.junit.Test; 7  8 import util.SqlSessionUtil; 9 10 public class StudentMapperTest {11     private Logger log = Logger.getLogger(StudentMapperTest.class);12     @Before13     public void setUp() throws Exception {14     }15 16     @Test17     public void test() {18         SqlSession sqlsession = null;19         try {20             sqlsession = SqlSessionUtil.getSqlSession();21             log.debug(sqlsession.getMapper(StudentMapper.class).getStudentCount());22         } catch (Exception e) {23             e.printStackTrace();24         } finally {25             SqlSessionUtil.closeSqlSession(sqlsession);26         }27     }28 }
View Code

util/util/SqlSessionUtil.java                        (工具类,负责获取和关闭sqlsession)

技术分享
 1 package util; 2  3 import java.io.IOException; 4  5 import org.apache.ibatis.io.Resources; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 10 public class SqlSessionUtil {11     private SqlSessionUtil() {12     }13     private static SqlSessionFactory sqlsession = null;14     15     static {16         try {17             sqlsession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));18         } catch (IOException e) {19             e.printStackTrace();20         }21     }22     23     public static SqlSession getSqlSession() {24         return sqlsession.openSession();25     }26     27     public static void closeSqlSession(SqlSession sqlsession) {28         sqlsession.close();29     }30 }
View Code

 

初识MyBatis