MyBatis学习简单入门

使用的是myEclipse8.5.

1>建立一个web project-MyBatis;

2>导入需要的jar包;mybatis-...jar,ojdbc14.jar等需要的jar包;

3>创建jdbc.properties,内容如下:(以下的四个值是必须的,也可以添加自己需要的,根据自己的情况来填写。)

driverClassName=

url=

username=

password=

4>创建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="jdbc.properties"></properties>

<typeAliases>

<typeAlias type="com.mybatis.SysUser" alias="user"/>

</typeAliases>

<environments default="development">

<environment id="development">

<transactionManager type="JDBC">

</transactionManager>

<dataSource type="POOLED">

<property name="driver" value="${driverClassName}"/>

<property name="url" value="${url}"/>

<property name="username" value="${username}"/>

<property name="password" value="${password}"/>

</dataSource>

</environment>

</environments>

<mappers>

<mapper resource="com/mybatis/sys_user.xml"/>

</mappers>

</configuration> 

5>创建数据库表映射类SysUser.java:

package com.mybatis;


import java.sql.Date;


public class SysUser {

    private String id;// 主键id


    private String techId;// 技术人员表id


    private String userName;// 用户账号


    private String userLevel;


    private String password;// 用户密码


    private String trueName;// 真是姓名


    private String openFlag;// 启用标识,1启用,0禁用


    private String defaultModule;// 默认首页


    private String remark;// 备注


    private Date createDate;


    private String createPname;


    private String modifyPname;


    private Date modifyDate;


    private String organName;


    private String organId;


    private String signature;


    private String cardId;


    private String phoneNo;


    public String getUserLevel() {

        return userLevel;

    }


    public void setUserLevel(String userLevel) {

        this.userLevel = userLevel;

    }


    public String getId() {

        return id;

    }


    public void setId(String id) {

        this.id = id;

    }


    public String getTechId() {

        return techId;

    }


    public void setTechId(String techId) {

        this.techId = techId;

    }


    public String getUserName() {

        return userName;

    }


    public void setUserName(String userName) {

        this.userName = userName;

    }


    public String getPassword() {

        return password;

    }


    public void setPassword(String password) {

        this.password = password;

    }


    public String getTrueName() {

        return trueName;

    }


    public void setTrueName(String trueName) {

        this.trueName = trueName;

    }


    public String getOpenFlag() {

        return openFlag;

    }


    public void setOpenFlag(String openFlag) {

        this.openFlag = openFlag;

    }


    public String getDefaultModule() {

        return defaultModule;

    }


    public void setDefaultModule(String defaultModule) {

        this.defaultModule = defaultModule;

    }


    public String getRemark() {

        return remark;

    }


    public void setRemark(String remark) {

        this.remark = remark;

    }


    public Date getCreateDate() {

        return createDate;

    }


    public void setCreateDate(Date createDate) {

        this.createDate = createDate;

    }


    public String getCreatePname() {

        return createPname;

    }


    public void setCreatePname(String createPname) {

        this.createPname = createPname;

    }


    public String getModifyPname() {

        return modifyPname;

    }


    public void setModifyPname(String modifyPname) {

        this.modifyPname = modifyPname;

    }


    public Date getModifyDate() {

        return modifyDate;

    }


    public void setModifyDate(Date modifyDate) {

        this.modifyDate = modifyDate;

    }


    public String getOrganName() {

        return organName;

    }


    public void setOrganName(String organName) {

        this.organName = organName;

    }


    public String getOrganId() {

        return organId;

    }


    public void setOrganId(String organId) {

        this.organId = organId;

    }


    public String getSignature() {

        return signature;

    }


    public void setSignature(String signature) {

        this.signature = signature;

    }


    public String getCardId() {

        return cardId;

    }


    public void setCardId(String cardId) {

        this.cardId = cardId;

    }


    public String getPhoneNo() {

        return phoneNo;

    }


    public void setPhoneNo(String phoneNo) {

        this.phoneNo = phoneNo;

    }


}

6>创建数据库数据查询sys_user.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.mybatis.IUserOperation">

<resultMap id="baseresultmap" type="com.mybatis.SysUser" >

    <id column="ID" property="id"/>

    <result column="TECH_ID" property="techId"/>

    <result column="USERNAME" property="userName" />

    <result column="USER_LEVEL" property="userLevel"/>

    <result column="ORGAN_NAME" property="organName"/>

    <result column="ORGAN_ID" property="organId" />

    <result column="PASSWORD" property="password" />

    <result column="TRUE_NAME" property="trueName" />

    <result column="OPEN_FLAG" property="openFlag" />

    <result column="DEFAULT_MODULE" property="defaultModule" />

    <result column="REMARK" property="remark" />

    <result column="CREATE_DATE" property="createDate" />

    <result column="CREATE_PNAME" property="createPname" />

    <result column="MODIFY_DATE" property="modifyDate" />

    <result column="MODIFY_PNAME" property="modifyPname" />

    <result column="CARD_ID" property="cardId" />

    <result column="SIGNATURE" property="signature"/>

    <result column="PHONE_NO" property="phoneNo" />

  </resultMap>

  <sql id="sys_user_column">

  ID as id,

        TRUE_NAME as trueName,

        ORGAN_NAME as organName,

        PHONE_NO as phoneNo

  </sql>

<select id="findbyid" parameterType="string" resultType="string">

select true_name from sys_user where id=#{id}

</select>

<select id="findallbyid" parameterType="string" resultMap="baseresultmap">

select * from sys_user where id=#{id}

</select>

<select id="findall" resultMap="baseresultmap">

select * from sys_user

</select>

<select id="findsomebyid" parameterType="string" resultMap="baseresultmap">

select

<include refid="sys_user_column"/>

from sys_user where id=#{id}

</select>

</mapper>

7>进行测试,创建MybatisTest.java:

package com.mybatis;


import java.io.IOException;

import java.io.Reader;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;


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.mybatis.dao.MybatisDao;


public class MybatisTest {

    MybatisDao dao;


    public static String resource = "mybatis_config.xml";


    public static Reader reader;


    public static SqlSessionFactoryBuilder builder;


    public static SqlSessionFactory factory;


    public static SqlSession session;


    public static String id;


    public static boolean really = false;


    public static List<SysUser> lsu;


    public static void main(String[] args) {

        MybatisTest test = new MybatisTest();


        try {

            reader = Resources.getResourceAsReader(resource);

            builder = new SqlSessionFactoryBuilder();

            factory = builder.build(reader);

            session = factory.openSession();

            // 通过session.getMapper来调用接口(但是对应.xmL中namespace要对应好。)

            IUserOperation iu = session.getMapper(IUserOperation.class);

            SysUser suser = (SysUser) iu.findUserById("4028a58d439f117201439f7effec0016");

            System.out.println(suser.getId());

            // 通过session.select..来调用接口。

            if (!really) {

                System.out.println("查询sys_user中的所有数据");

                lsu = test.findAll();

                for (int i = 0; i < lsu.size(); i++) {

                    SysUser user = lsu.get(i);

                    System.out.println(user.getId() + "@" + user.getTrueName() + "@" + user.getCardId() + "@"

                            + user.getPhoneNo());

                }


            }

            /**

             * 输入id号,查询数据;

             */

            if (really) {

                System.out.println("请输入查询id号:");

                Scanner sc = new Scanner(System.in);

                if (sc.hasNext()) {

                    id = sc.nextLine().toString();

                    System.out.println(test.findUserById());

                    System.out.println("------------findnamebyid");

                    System.out.println(test.findNameById());


                    System.out.println("查询部分数据属性");

                    SysUser su = test.findSomeById();

                    System.out.println(su.getId() + "@" + su.getTrueName() + "@" + su.getOrganName() + "@"

                            + su.getPhoneNo());

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

        System.exit(0);

    }


    /**

     * 从数据库查询,根据id查询user

     */

    public String findUserById() {

        session = factory.openSession();

        SysUser user = (SysUser) session.selectOne("findallbyid", id);

        session.commit();

        return user.getId() + "@" + user.getTrueName() + "@" + user.getCardId() + "@" + user.getPhoneNo();

    }


    /**

     * 从数据库查询,根据id查询name

     */

    public String findNameById() {

        session = factory.openSession();

        String name = (String) session.selectOne("findbyid", id);

        return name;

    }


    /**

     * 查询sys_user中所有数据

     */

    public List<SysUser> findAll() {

        session = factory.openSession();

        List<SysUser> ls = new ArrayList<SysUser>();

        ls = session.selectList("findall");

        return ls;

    }


    /**

     * 根据id查询数据部分属性

     */

    public SysUser findSomeById() {

        session = factory.openSession();

        SysUser s = (SysUser) session.selectOne("findsomebyid", id);

        return s;

    }


    public MybatisDao getDao() {

        return dao;

    }


    public void setDao(MybatisDao dao) {

        this.dao = dao;

    }


}

8>在以上测试类中,查询数据时,有两种方法,其中session.getMapper,需要的IUserOperation接口,创建方法如下:

package com.mybatis;


import java.util.List;


import org.apache.ibatis.annotations.Select;


public interface IUserOperation {

    @Select("select * from sys_user WHERE id = #{id}")

    public SysUser findUserById(String id);// 根据id查询用户信息


    public String findNameById();// 根据id查询用户姓名或者其他属性


    public List<SysUser> findAll();// 查询所有用户


    public SysUser findSomeById();// 根据id查询用户部分属性


}

9>以上。全部建立完毕后,即可测试运行。具体的配置文件位置等,可以按照自己的习惯,因为仅是将mybatis运作起来,暂时没有太多的要求,下一步mybatis-spring-webwork的整合的时候,会需要注意一点。

关于为什么使用,mybatis,webwork框架是因为项目需要,自己重新学习一边,还有许多的不足,如果有不对的地方,希望您指出来,让我们共同进步吧,呵呵。

你可能感兴趣的:(mybatis,学习)