springMVC+MyBatis+Spring+maven 整合(1)

1.首先第一步.部署mybatis ;

1.1 下载myBatis 

MyBits前身是iBitis,相对于Hibernate而言,它是半自动化ORM框架。由于老板对性能要求的比较苛刻,不得不放弃我亲爱的hibernate,转而学习并使用mybatis,在此之前我对mybatis也并不熟悉,如有不对的地方,欢迎指正,也希望对想学习mybitis的同窗们有所帮助。
       鉴于我的测试数据库是mysql,同仁们现在把mysql装好,然后准备好mysql驱动以及 下载mybitis(
http://code.google.com/p/mybatis/)。 

我用的是maven. 就直接在pom 文件里面写了.

 

<dependencies>
         
        <!-- db -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.5</version>
        </dependency>
         
         
        <!-- 加入mysql驱动依赖包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
</dependency>

2.新建数据表

DROP TABLE IF EXISTS `t_test`;
CREATE TABLE `t_test` (
  `id` int(11) NOT NULL,
  `userName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_test
-- ----------------------------
INSERT INTO `t_test` VALUES ('1', '2');

3.用mybatis-generator 自动生成代码

 创建一个配置文件,如conf.xml,此处文件名自己命名,没有命名方面的特殊要求, 可以参考doc文档里的配置文件写的,我的如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动包位置 -->
    <!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
    <classPathEntry location="E:\data\.m2\repository\mysql\mysql-connector-java\5.1.25\mysql-connector-java-5.1.25.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库链接URL、用户名、密码 -->
         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/c_sai" userId="root" password=""> 
        <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.test.model" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的映射文件包名和位置 -->
        <sqlMapGenerator targetPackage="com.test.mapping" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.dao" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="t_test" domainObjectName="TTest" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> 
    </context>
</generatorConfiguration>

 执行jar 文件

E:\data\Users\Administrator\Downloads\generator> java -jar mybatis-generator-cor
e-1.3.2.jar -configfile  generator.xml -overwrite
MyBatis Generator finished successfully.

 生成代码如下

package com.test.model;

public class TTest {
    private Integer id;

    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
}

 

package com.test.dao;

import com.test.model.TTest;

public interface TTestMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TTest record);

    int insertSelective(TTest record);

    TTest selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(TTest record);

    int updateByPrimaryKey(TTest record);
}

 

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="com.test.dao.TTestMapper" >
  <resultMap id="BaseResultMap" type="com.test.model.TTest" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="userName" property="username" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, userName
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_test
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_test
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.test.model.TTest" >
    insert into t_test (id, userName)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.test.model.TTest" >
    insert into t_test
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        userName,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.test.model.TTest" >
    update t_test
    <set >
      <if test="username != null" >
        userName = #{username,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.test.model.TTest" >
    update t_test
    set userName = #{username,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

 

编写mybatis 配置文件

mybatis-config.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://127.0.0.1:3306/c_sai" />
                <property name="username" value="root" />
                <property name="password" value="" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
         <mapper resource="com\test\mapping\TTestMapper.xml" />
    </mappers>
</configuration>

编写测试类

package com.jefry;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.test.model.TTest;

public class Test {
    static String resource = "mybatis-config.xml";

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // User.selectUser中User对应UserMapper.xml文件中标签<mapper
            // namespace="com.test.dao.TTestMapper"> namespace的值
            // selectUser 对应UserMapper.xml文件中标签<select id="selectUser"
            // parameterType="int" resultType="com.jefry.User">中id值
            TTest tt = session.selectOne("com.test.dao.TTestMapper.selectByPrimaryKey", 1);
            System.out.println("tt.getName()=" + tt.getUsername());
        } finally {
            session.close();
        }
    }

}

 

结果:

tt.getName()=2

到此为止mybatis 部署成功.

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(springMVC+MyBatis+Spring+maven 整合(1))