市场上所用的框架

  • Hibernate
  • jdbcTemplate
  • ibatis
  • mybatis

mybatis的优点

  • 对jdbc做了很好的封装
  • 容易掌握
  • 灵活性强

MyBatis的安装包

log4j.properties
mybatis-3.1.1-bundle.zip
mybatis-spring-1.0.0-bundle.zip
mysql-connector-java-xxx-bin.jar

MyBatis的第一个例子

准备数据

drop table if exists person_test;

create table person_test(  
    id int(10) not null auto_increment,
    name varchar(10),
    gender int(1),
    address varchar(50),
    birthday date,
    primary key(id)
);

insert into person_test values(1, '刘备', 1, '蜀国', '2014-10-11');  

maven的pom.xml依赖项

<dependencies>  
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
        </dependency>
    </dependencies>

log4j的配置

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  

实体类Person

public class Person {  
    private Integer id;
    private String name;
    private Integer gender;
    private String address;
    private Date birthday;
    //...get set
}    

mybatis主配置文件SqlMapConfig.xml

<?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>  
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql:///mybatis" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!-- 
        管理每张表的映射文件
     -->
    <mappers>
        <mapper resource="com/itbto/mapper/PersonTestMapper.xml"/>
    </mappers>
</configuration>  

映射文件PersonTestMapper.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">

<!--  
    namespace:映射文件的命名空间,规范是映射文件的包的全路径
 -->
<mapper namespace="com.itbto.mapper.PersonTestMapper">  
    <!-- 
        id:sql的唯一标识
        parameterType:传递给sql的参数的数据类型
        resultType:返回数据结果的类型
        #{id}:用于接收参数的语法{}的内容,如果是接收一个参数内容任意select * from person_test where id = ?,
        #{}使用预编译的方式生成sql,防止sql注入
     -->
    <select id="selectPersonById" parameterType="java.lang.Integer" resultType="com.itbto.mode.Person">
        select * from person_test where id = #{id}
    </select>
</mapper>  

测试类

public class MyBatisTest {

    SqlSessionFactory sessionFactory;

    @Before
    public void setUp() throws Exception{
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        sessionFactory = new SqlSessionFactoryBuilder().build(in);
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("close........");
    }

    @Test
    public void test(){
        SqlSession session = sessionFactory.openSession();
        try {
            //selectOne:第一个参数:要执行的sql,命名空间.sql的id
            //第二个参数是传递给sql的实际参数
            Person person = session.selectOne("com.itbto.mapper.PersonTestMapper.selectPersonById", 1);
            System.out.println(person);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            session.close();
        }
    }
}