Idea搭建mybatis环境demo

这两天看看mybatis,这个轻量级orm框架,看后面把它整合进项目中。把JDBC分离出来。这里只是简单环境搭建,未涉及原理。

1.创建工程

  这里为了方便直接用一个模板

创建完毕

2.引入mybatis所需jar包

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

  //测试相关
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  //日志相关
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>

3.创建一个实体类对应数据字段,并在数据库中创建对应的数据表

public class User implements Serializable {

    private static final long serialVersionUID = 8104961490512068314L;
    private int id;
    private String name;
    private String dept;
    private String phone;
    private String website;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", dept='" + dept + '\'' +
                ", phone='" + phone + '\'' +
                ", website='" + website + '\'' +
                '}';
    }

}  

4.添加mysql配置文件,mybatis配置文件

mybatis-config.xml

<configuration>
    <properties resource="mysql.properties"></properties>


    <typeAliases>
        <!-- 别名方式1,一个一个的配置 type中放置的是类的全路径,alias中放置的是类别名
        <typeAliase type="com.mybatis.demo.Entity.User" alias="UserBean"/> -->
        <!-- 别名方式2,自动扫描,将JAVA类的类名作为类的类别名 -->
        <!--<package name="com.mybatis.demo.Entity"/>-->
        <typeAlias alias="User" type="com.mybatis.demo.Entity.User"/>
    </typeAliases>

    <!-- 配置mybatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
            <transactionManager type="JDBC"/>

            <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
            <!-- POOLED 表示支持JDBC数据源连接池 -->
            <!-- UNPOOLED 表示不支持数据源连接池 -->
            <!-- JNDI 表示支持外部数据源连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.databaseurl}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <!-- 映射文件方式1,一个一个的配置-->
        <mapper resource="mapper/UserMapper.xml"/>
        <!-- 映射文件方式2,自动扫描包内的Mapper接口与配置文件 -->
        <!--<package name="com.mybatis.demo"/>-->
    </mappers>

</configuration>

mysql.properties:

jdbc.databaseurl=jdbc:mysql:///javaweb_community?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=
jdbc.maxActive=100
jdbc.maxWait=5000
jdbc.filters=wall,stat 

ps: 这里mysql的jar包版本在6.0以上的和以前版本有一点差异。

5.添加mapper类接口以及对应mapper.xml

package com.mybatis.demo.mapper;


import com.mybatis.demo.Entity.User;

public interface UserMapper {

    User GetUserByID(Integer id) throws Exception;


}

 

 

<mapper namespace="com.mybatis.demo.mapper.UserMapper">
    <!-- 自定义返回结果集 -->
    <resultMap id="userMap" type="User">
        <id property="id" column="id" javaType="java.lang.Integer"></id>
        <result property="username" column="username" javaType="java.lang.String"></result>
        <result property="password" column="password" javaType="java.lang.String"></result>
        <result property="account" column="account" javaType="java.lang.Double"></result>
    </resultMap>

<select id="GetUserByID" parameterType="int" resultMap="userMap"> select * from `user` where id = #{id} </select> </mapper>

6.在配置文件中注册该xml.

 

7.编写单元测试,通过sqlSession 操作数据库

public class AppTest 
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {

        try {
            //使用MyBatis提供的Resources类加载mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis/mybatis-config.xml");
            //构建sqlSession的工厂
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

            SqlSession session= sessionFactory.openSession();
            UserMapper mapper=session.getMapper(UserMapper.class);
            User user= mapper.GetUserByID(1);
            System.out.println(user.toString());

            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

posted @ 2018-05-12 10:52  小阿Q的博客  阅读(27987)  评论(0编辑  收藏  举报