mybatis项目构建过程附源码下载

来源:互联网 发布:js控制button点击 编辑:程序博客网 时间:2024/04/30 18:55

集成环境:
IntelliJ IDEA 2016.3.2
JRE: 1.8.0_112-release-408-b6 x86_64

本地安装mysql,创建数据库user.db,新建表名为Person
建表语句如下:

CREATE TABLE `Person` (  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,  `userName` varchar(255) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `mobilePhone` varchar(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=10008 DEFAULT CHARSET=utf8;

完成以上准备即可进入下面的构建过程,进行测试学习。
1、新建一个webapp项目即可。具体构建webapp过程 参考地址:
点击链接

2、在WEB-INF下新建lib文件夹,添加数据库连接的两个jar包,导入到內库mybatis-3.2.0-SNAPSHOT.jar和mysql-connector-java-5.1.22-bin.jar

3、项目的目录结构如下:
这里写图片描述

4、根据目录结构构建相关配置文件和java类包
首先,在model包下新建Person.java类文件。Person.java文件内容如下:

package model;public class Person {    private int id;    private String userName ;    private int age ;    private String mobilePhone ;    public  Person(){}    public Person(int id,String userName, int age, String mobilePhone) {        this.id = id;        this.userName = userName;        this.age = age;        this.mobilePhone = mobilePhone;    }    public String getUserName() {        return userName;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public void setUserName(String userName) {        this.userName = userName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getMobilePhone() {        return mobilePhone;    }    public void setMobilePhone(String mobilePhone) {        this.mobilePhone = mobilePhone;    }    @Override    public String toString() {        return "Person{" +                "userName='" + userName + '\'' +                ", age=" + age +                ", mobilePhone='" + mobilePhone + '\'' +                '}';    }}

然后,构建MybatisUtil.java工具包,用于获取连接数据的SqlSession对象,关于其原理和源码分析网上有详细的资料供查阅,我这里主要讲解一下构建过程。
代码如下:

package utils;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 java.io.IOException;import java.io.Reader;/** * Created by roly on 2017/6/23. */public class MybatisUtil {    private final  static SqlSessionFactory sqlSessionFactory;    static {        String resource="mybatis-config.xml";        Reader reader =null;        try {            reader = Resources.getResourceAsReader(resource);        } catch (IOException e) {            e.printStackTrace();        }        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);    }    /**     * 获取SqlSessionFactory     * @return SqlSessionFactory     */    public static SqlSessionFactory getSqlSessionFactory(){        return sqlSessionFactory;    }    /**     * 获取SqlSession     * @return SqlSession     */    public static SqlSession getSqlSession(){        return sqlSessionFactory.openSession();    }    /**     * 关闭SqlSession     */    public  static void closeSession(SqlSession sqlSession){        if (sqlSession!=null)            sqlSession.close();    }}

5、配置文件。
在resources文件夹目录下新建连接数据库的配置文件mybatis-config.xml和config.properties。这里要注意在mybatis-config.xml的配置文件总不要忘记映射文件的配置 <mapper resource="mapper/Person.xml"/>
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>    <properties resource="config.properties"/>    <typeAliases>        <typeAlias type="model.Person" alias="Person"/>    </typeAliases>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="${driver}"/>                <property name="url" value="${url}"/>                <property name="username" value="${username}"/>                <property name="password" value="${password}"/>            </dataSource>        </environment>    </environments>    <mappers>        <mapper resource="mapper/Person.xml"/>    </mappers></configuration>

config.properties文件内容如下:

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/userusername=rootpassword=

6、在resouse/mapper下新建映射文件Person.xml。主要映射一些mysql语句。注意select标签一定要带映射类的结果类型resultType=”model.Person”,具体代码如下:

<?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">    <insert id="insertPerson" parameterType="Person" >        INSERT INTO PERSON(ID,USERNAME,AGE,MOBILEPHONE)VALUES (#{id},#{userName},#{age},#{mobilePhone})    </insert>    <select id="queryById" parameterType="int" resultType="model.Person">        SELECT * FROM PERSON WHERE ID=#{id}    </select>    <update id="updatePerson" parameterType="Person" >        UPDATE PERSON SET USERNAME=#{userName},AGE=#{age},MOBILEPHONE=#{mobilePhone} WHERE mobilePhone=#{mobilePhone}    </update>    <delete id="deletePerson" parameterType="String">        DELETE FROM PERSON  WHERE mobilePhone=#{mobilePhone}    </delete>    <insert id="insertRoly" parameterType="Person">        INSERT INTO Person(username,age,mobilephone) VALUES (#{userName},#{age},#{mobilePhone})    </insert>    <select id="selectRoly" parameterType="String"  resultType="model.Person">        SELECT * FROM Person WHERE mobilephone=#{mobilePhone}    </select></mapper>

7、构建测试类UserTest.java
代码如下:

package com.user.test;import model.Person;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import utils.MybatisUtil;import java.util.List;public class UserTest {    SqlSession sqlSession ;    @Test    public void insertPerson(){        sqlSession = MybatisUtil.getSqlSession();//        int id = 10000;        String userName = "test";        int age = 18;        String mobilePhone = "11111111";        Person person = new Person();//        person.setId(id);        person.setAge(age);        person.setUserName(userName);        person.setMobilePhone(mobilePhone);        try{            sqlSession.insert("insertPerson",person);            sqlSession.commit();        }catch (Exception e){            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }    @Test    public void queryById(){        sqlSession = MybatisUtil.getSqlSession();        int id = 10002;        try{            Person person = sqlSession.selectOne("queryById",id);            sqlSession.commit();            if(person == null){                System.out.println("Person_null");            }else{                System.out.println(person.getUserName());            }        }catch (Exception e){            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }    @Test    public void insertData() {        sqlSession = MybatisUtil.getSqlSession();        String username = "test";        int age = 19;        String mobilephone = "222222222";        Person person = new Person();        person.setUserName(username);        person.setAge(age);        person.setMobilePhone(mobilephone);        try {            sqlSession.insert("insertRoly",person);            sqlSession.commit();        }catch (Exception e){            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }    @Test    public void selectData() {        sqlSession = MybatisUtil.getSqlSession();        try {            List<Person> persons = sqlSession.selectList("selectRoly","222222222");            sqlSession.commit();            if (persons!=null && persons.size()!=0) {                for (Person parms:persons) {                    System.out.println(parms.toString());                }            }else {                System.out.println("person is null");            }        }catch (Exception e){            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }    @Test    public void updateData() {        sqlSession = MybatisUtil.getSqlSession();        String userName = "test";        int age = 18;        String mobilePhone = "222222222";        Person person = new Person();//        person.setId(id);        person.setAge(age);        person.setUserName(userName);        person.setMobilePhone(mobilePhone);        try {            sqlSession.update("updatePerson",person);            sqlSession.commit();        }catch (Exception e) {            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }    @Test    public void deleteData() {        sqlSession = MybatisUtil.getSqlSession();        try {            String mobilePhone = "11111111";            sqlSession.delete("deletePerson",mobilePhone);            sqlSession.commit();        }catch (Exception e) {            e.printStackTrace();        }finally {            MybatisUtil.closeSession(sqlSession);        }    }}

好了,整个mybatis项目的增删改查映射操作完成。这个只是一个简单的构建过程。附上源码下载地址
点击下载

原创粉丝点击