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

 

  二、基础数据准备

  于数据库被建表,以及长始末。表结构使图:

图片 2

  创建实体类

 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查找用户,最终获控制高出口结果

图片 3

 

网站地图xml地图