• Maven+MyBatis 初试


      工作中一直使用的都是Hibernate,总是听见有人拿Mybatis和Hibernate做比较,今天尝试来看看。

      一、用Maven建立web项目

      此处参见 http://www.cnblogs.com/adamJin/p/6930122.html  第一步,其中pom.xml加入MyBatis依赖。  

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.adam</groupId>
      <artifactId>TestMybatis</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>
      
       <properties>  
            <!-- spring版本号 -->  
            <spring.version>4.0.2.RELEASE</spring.version>  
            <!-- mybatis版本号 -->  
            <mybatis.version>3.2.6</mybatis.version>  
            <!-- log4j日志文件管理包版本 -->  
            <slf4j.version>1.7.7</slf4j.version>  
            <log4j.version>1.2.17</log4j.version>  
        </properties>  
      
        <dependencies>  
            <dependency>  
                <groupId>junit</groupId>  
                <artifactId>junit</artifactId>  
                <version>4.11</version>  
                <!-- 表示开发的时候引入,发布的时候不会加载此包 -->  
                <scope>test</scope>  
            </dependency>  
            <!-- spring核心包 -->  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-core</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-web</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-oxm</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-tx</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-jdbc</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-webmvc</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-aop</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-context-support</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-test</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <!-- mybatis核心包 -->  
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis</artifactId>  
                <version>${mybatis.version}</version>  
            </dependency>  
            <!-- mybatis/spring包 -->  
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis-spring</artifactId>  
                <version>1.2.2</version>  
            </dependency>  
            <!-- 导入java ee jar 包 -->  
            <dependency>  
                <groupId>javax</groupId>  
                <artifactId>javaee-api</artifactId>  
                <version>7.0</version>  
            </dependency>  
            <!-- 导入Mysql数据库链接jar包 -->  
            <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>5.1.30</version>  
            </dependency>  
            <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->  
            <dependency>  
                <groupId>commons-dbcp</groupId>  
                <artifactId>commons-dbcp</artifactId>  
                <version>1.2.2</version>  
            </dependency>  
            <!-- JSTL标签类 -->  
            <dependency>  
                <groupId>jstl</groupId>  
                <artifactId>jstl</artifactId>  
                <version>1.2</version>  
            </dependency>  
            <!-- 日志文件管理包 -->  
            <!-- log start -->  
            <dependency>  
                <groupId>log4j</groupId>  
                <artifactId>log4j</artifactId>  
                <version>${log4j.version}</version>  
            </dependency>  
              
              
            <!-- 格式化对象,方便输出日志 -->  
            <dependency>  
                <groupId>com.alibaba</groupId>  
                <artifactId>fastjson</artifactId>  
                <version>1.1.41</version>  
            </dependency>  
      
      
            <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-api</artifactId>  
                <version>${slf4j.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-log4j12</artifactId>  
                <version>${slf4j.version}</version>  
            </dependency>  
            <!-- log end -->  
            <!-- 映入JSON -->  
            <dependency>  
                <groupId>org.codehaus.jackson</groupId>  
                <artifactId>jackson-mapper-asl</artifactId>  
                <version>1.9.13</version>  
            </dependency>  
            <!-- 上传组件包 -->  
            <dependency>  
                <groupId>commons-fileupload</groupId>  
                <artifactId>commons-fileupload</artifactId>  
                <version>1.3.1</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-io</groupId>  
                <artifactId>commons-io</artifactId>  
                <version>2.4</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-codec</groupId>  
                <artifactId>commons-codec</artifactId>  
                <version>1.9</version>  
            </dependency>  
              
              
        </dependencies> 
    </project>

      创建完成后,结构如下

      二、基础数据准备

      在数据库中建表,以及添加内容。表结构如图:

      创建实体类

     1 package com.adam.domain;
     2 
     3 import java.io.Serializable;
     4 import java.util.Date;
     5 
     6 import javax.persistence.Entity;
     7 import javax.persistence.Table;
     8 
     9 public class User implements Serializable {
    10     private int userId;
    11     private String userName;
    12     private String password;
    13     private int credits;
    14     private String lastIp;
    15     private Date lastVisit;
    16 
    17     public String toString() {
    18         return "User : {userId = " + userId + ", userName = " + userName + ", password = " + password + ", credits = "
    19                 + credits + ", lastIp = " + lastIp + ", lastVisit = " + lastVisit + "}";
    20     }
    21 
    22     public int getUserId() {
    23         return userId;
    24     }
    25 
    26     public void setUserId(int userId) {
    27         this.userId = userId;
    28     }
    29 
    30     public String getUserName() {
    31         return userName;
    32     }
    33 
    34     public void setUserName(String userName) {
    35         this.userName = userName;
    36     }
    37 
    38     public String getPassword() {
    39         return password;
    40     }
    41 
    42     public void setPassword(String password) {
    43         this.password = password;
    44     }
    45 
    46     public int getCredits() {
    47         return credits;
    48     }
    49 
    50     public void setCredits(int credits) {
    51         this.credits = credits;
    52     }
    53 
    54     public String getLastIp() {
    55         return lastIp;
    56     }
    57 
    58     public void setLastIp(String lastIp) {
    59         this.lastIp = lastIp;
    60     }
    61 
    62     public Date getLastVisit() {
    63         return lastVisit;
    64     }
    65 
    66     public void setLastVisit(Date lastVisit) {
    67         this.lastVisit = lastVisit;
    68     }
    69 
    70 }

      此处注意,数据表中的字段和实体类的变量名是否一致,影响到后面的写法。简单的做法是保持一致,在查询获得实体对象时可以直接转换。此例中为不一致的。

      三、建立配置文件

      创建conf.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>
        <!-- 注意此处设置的别名,在映射文件处有用处 -->
        <typeAliases>
            <typeAlias alias="User" type="com.adam.domain.User" />
        </typeAliases>
        <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://localhost:3306/sampledb" />
                    <property name="username" value="root" />
                    <property name="password" value="adam" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!-- 注册userMapper.xml文件, userMapper.xml位于com.adam.mapping这个包下,所以resource写成com/adam/mapping/userMapper.xml -->
            <mapper resource="com/adam/mapping/userMapper.xml" />
        </mappers>
    </configuration>

      mappers 中注册的是下面第四步建立的映射文件

      四、建立映射文件

      创建userMapper.xml。

      此处分两种。如果上述第二步中表字段名和实体成员变量名称一致且在配置文件中起了别名,可以直接在查询时使用 resultType="别名":

    <?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.adam.mapping.userMapper">
        <select id="selectUserByID" parameterType="int" resultType="User">
            select * from `t_user` where user_id = #{userId}
        </select>
    </mapper>

      如果,表字段名和实体成员变量名称不一致,则需要重新匹配,并在查询中使用 resultMap=“mapId”:

    <?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.adam.mapping.userMapper">
        <resultMap type="com.adam.domain.User" id="User">
            <id property="userId" column="user_id" />
            <result property="userName" column="user_name" />
            <result property="password" column="password" />
            <result property="credits" column="credits" />
            <result property="lastIp" column="last_ip" />
            <result property="lastVisit" column="last_visit" />
    
        </resultMap>
        <select id="selectUserByID" parameterType="int" resultMap="User">
            select * from `t_user` where user_id = #{userId}
        </select>
    </mapper>

      如此,便完成了MyBatis接入。

      五、测试

      建立测试文件Test.java

      

     1 import java.io.Reader;
     2 
     3 import org.apache.ibatis.io.Resources;
     4 import org.apache.ibatis.session.SqlSession;
     5 import org.apache.ibatis.session.SqlSessionFactory;
     6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     7 
     8 import com.adam.domain.User;
     9 
    10 public class Test {
    11     private static SqlSessionFactory sqlSessionFactory;
    12     private static Reader reader; 
    13 
    14     static{
    15         try{
    16             reader    = Resources.getResourceAsReader("conf.xml");
    17             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    18         }catch(Exception e){
    19             e.printStackTrace();
    20         }
    21     }
    22 
    23     public static SqlSessionFactory getSession(){
    24         return sqlSessionFactory;
    25     }
    26     
    27     public static void main(String[] args) {
    28         SqlSession session = sqlSessionFactory.openSession();
    29         try {
    30         User user = (User) session.selectOne("com.adam.mapping.userMapper.selectUserByID", 1);
    31         System.out.println(user.toString());
    32         } finally {
    33         session.close();
    34         }
    35     }
    36 }

      根据id查找用户,最终得到控制台输出结果

  • 相关阅读:
    [Re] Spring-4(SourceCode)
    [Re] Spring-3(JdbcTemplate)
    [Re] Spring-2(IOC+AOP)
    [Re] Spring-1(bean)
    08-MyBatis(2)
    08-传输层(7)
    07-传输层(6)
    06-传输层(5)
    05-传输层(4)
    ALS推荐算法
  • 原文地址:https://www.cnblogs.com/adamJin/p/7365592.html
Copyright © 2020-2023  润新知