Mybatis基础入门一

本文介绍了一个使用MyBatis实现的成员与任务管理系统的详细设计方案。系统通过定义数据库表结构、配置MyBatis环境、编写Mapper文件及POJO类等步骤实现了成员信息及其关联任务的管理,并提供了一个具体的测试案例。
摘要由CSDN通过智能技术生成

数据准备:

CREATE TABLE MEMBER (
MEMBER_ID NUMBER(10, 0),
FIRST_NAME VARCHAR2(400) NOT NULL,
LAST_NAME VARCHAR2(400) NOT NULL,
ADDRESS VARCHAR2(1000),
PHONE VARCHAR2(400),
PRIMARY KEY (MEMBER_ID));

CREATE TABLE TASK (
TASK_ID NUMBER(10, 0),
MEMBER_ID NUMBER(10, 0),
CONTENT VARCHAR2(1000),
DUE_DATE DATE,
PRIMARY KEY (TASK_ID),
FOREIGN KEY (MEMBER_ID) REFERENCES MEMBER (MEMBER_ID));

INSERT INTO MEMBER (MEMBER_ID, FIRST_NAME, LAST_NAME,PHONE) VALUES(1,'Alex', 'Brown', '635874');
INSERT INTO MEMBER (MEMBER_ID, FIRST_NAME, LAST_NAME,PHONE) VALUES(2,'Ada', 'Lee', '536952');
INSERT INTO MEMBER (MEMBER_ID, FIRST_NAME, LAST_NAME,PHONE) VALUES(3,'Candy', 'Law', '362548');
INSERT INTO MEMBER (MEMBER_ID, FIRST_NAME, LAST_NAME,PHONE) VALUES(4,'Vincent', 'Xu', '123698');

INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (1, 1 ,'Kill Bill Gates.', TO_DATE('2012-12-31', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (2, 1 ,'Earn USD 1 billion.', TO_DATE('2033-01-01', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (3, 1 ,'Worldwide trip.', TO_DATE('2020-03-03', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (4, 2 ,'Learn Java.', TO_DATE('2012-09-08', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (5, 2 ,'Learn Ruby.', TO_DATE('2012-11-12', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (6, 3 ,'Finish job 1.', TO_DATE('2013-04-01', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (7, 3 ,'Finish job 2.', TO_DATE('2013-06-06', 'YYYY-MM-DD'));
INSERT INTO TASK (TASK_ID,MEMBER_ID, CONTENT, DUE_DATE) VALUES (8, 3 ,'Finish job 3.', TO_DATE('2014-02-28', 'YYYY-MM-DD'));

COMMIT;



目录结构:

[img]

 [/img]

 

mybatis-config.xml(mybatis的配置文件)

 

    <!-- db setting -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@192.168.2.136:1521:dev" />
                <property name="username" value="cnt5_training" />
                <property name="password" value="p" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 关联mapper文件 -->
        <mapper resource="com/core/traininig/mybatisquiz/MemberMapper.xml" />
    </mappers>
 

 

MemberMapper.xml(POJO 与 sql 的映射文件)

 

<?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会调用该映射文件来进行CRUD -->
<mapper namespace="com.core.traininig.mybatisquiz.MemberMapper">

<resultMap id="memberWithTask" type="com.core.traininig.entity.Member">
        <result property="memberId" column="MEMBER_ID" />
        <result property="firstName" column="FIRST_NAME" />
        <result property="lastName" column="LAST_NAME" />
        <result property="address" column="ADDRESS" />
        <result property="phone" column="PNONE" />
        <collection property="tasks"
            ofType="com.core.traininig.entity.Task" column="MEMBER_ID" javaType="ArrayList">
            <result property="taskId" column="TASK_ID" />
            <result property="memberId" column="MEMBER_ID" />
            <result property="content" column="CONTENT" />
            <result property="dueDate" column="DUE_DATE" />
        </collection>
    </resultMap>

    <!-- id要与XXXMapper.java 的方法名一致-->
    <select id="getAllMembers" parameterType="map"
        resultMap="memberWithTask">
    SELECT m.MEMBER_ID AS ID, m.FIRST_NAME, m.LAST_NAME, m.ADDRESS, m.PHONE,t.TASK_ID,
        t.MEMBER_ID, t.CONTENT, t.DUE_DATE
           FROM MEMBER m LEFT JOIN TASK t ON m.MEMBER_ID = t.MEMBER_ID
    ORDER BY m.FIRST_NAME, t.DUE_DATE DESC
    </select>

</mapper>
 

 MemberMapper.java

import java.util.List;

import com.core.traininig.entity.Member;

/**
 * @author aron.tang
 *
 */
public interface MemberMapper {
   List<Member> getAllMembers();
}

 

Member.java

 

import java.util.List;

/**
 * @author aron.tang
 *
 */
public class Member {
    private int memberId;
    private String firstName;
    private String lastName;
    private String address;
    private String phone;
    private List<Task> tasks;
    /**
     * @return the memberId
     */
    public int getMemberId() {
        return memberId;
    }
    /**
     * @param memberId the memberId to set
     */
    public void setMemberId(final int memberId) {
        this.memberId = memberId;
    }
    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }
    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }
    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }
    /**
     * @param lastName the lastName to set
     */
    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }
    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }
    /**
     * @param address the address to set
     */
    public void setAddress(final String address) {
        this.address = address;
    }
    /**
     * @return the phone
     */
    public String getPhone() {
        return phone;
    }
    /**
     * @param phone the phone to set
     */
    public void setPhone(final String phone) {
        this.phone = phone;
    }
    /**
     * @return the tasks
     */
    public List<Task> getTasks() {
        return tasks;
    }
    /**
     * @param tasks the tasks to set
     */
    public void setTasks(final List<Task> tasks) {
        this.tasks = tasks;
    }



}
 

 

Task.java

import java.util.Date;

/**
 * @author aron.tang
 *
 */
public class Task {
    private int taskId;
    private int memberId;
    private String content;
    private Date dueDate;
    /**
     * @return the taskId
     */
    public int getTaskId() {
        return taskId;
    }
    /**
     * @param taskId the taskId to set
     */
    public void setTaskId(final int taskId) {
        this.taskId = taskId;
    }
    /**
     * @return the memberId
     */
    public int getMemberId() {
        return memberId;
    }
    /**
     * @param memberId the memberId to set
     */
    public void setMemberId(final int memberId) {
        this.memberId = memberId;
    }
    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }
    /**
     * @param content the content to set
     */
    public void setContent(final String content) {
        this.content = content;
    }
    /**
     * @return the dueDate
     */
    public Date getDueDate() {
        return dueDate;
    }
    /**
     * @param dueDate the dueDate to set
     */
    public void setDueDate(final Date dueDate) {
        this.dueDate = dueDate;
    }

}
 

 

测试类MemberManager.java

 

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

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.core.traininig.entity.Member;
import com.core.traininig.entity.Task;

/**
 * @author aron.tang
 */
public class MemberManager {
    private static SqlSessionFactory sqlSessionFactory;

    public static void main(final String[] args) throws IOException {
        // load the setting file of mybatis.
        final String resource = "com/core/traininig/mybatisquiz/mybatis-config.xml";
        final InputStream inputStream = Resources.getResourceAsStream(resource);
        // build the SqlSessionFactory instance which manage the session when access DB.
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        printMembers();
    }

    public static List<Member> getAllMembers() {
        // open the session then can access the assigned DB 
        final SqlSession session = sqlSessionFactory.openSession();
        // get the mapper which map the sql to POJO.
        final MemberMapper mapper = session.getMapper(MemberMapper.class);
        return mapper.getAllMembers();

    }

    public static void printMembers() {
        final MemberMapper mapper = getMapper();
        final List<Member> members = mapper.getAllMembers();
        System.out.println("There are total " + members.size() + " members");
        System.out.println("================================================");
        for (final Member m : members) {
            System.out.println(m.getFirstName() + " " + m.getLastName() + " has " + m.getTasks().size() + " tasks. ");
            for (final Task t : m.getTasks()) {
                System.out.println("{" + t.getContent() + "} to be done before " + parseDate(t.getDueDate()));
            }
            System.out.println();
        }
        closeSession();
    }

    public static String parseDate(final Date date) {
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        final String result = df.format(date);
        return result;
    }
    
    private static MemberMapper getMapper() {
        final SqlSession session = sqlSessionFactory.openSession();
        final MemberMapper mapper = session.getMapper(MemberMapper.class);
        return mapper;
    }
    
    private static void closeSession() {
        final SqlSession session = sqlSessionFactory.openSession();
        if (session != null) {
            session.close();
        }
    }

}
 

 

测试结果:



 主要用到的jar包: 
mybatis-3.0.5.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值