Mybatis基础入门二

Mybatis 除了可以在xml定义sql外, 还可以通过java来生成sql.

生成sql的java类 EntityProvider:
// Copyright (c) 1998-2013 Core Solutions Limited. All rights reserved.

package com.core.traininig.mybatisquiz;

import static org.apache.ibatis.jdbc.SqlBuilder.BEGIN;
import static org.apache.ibatis.jdbc.SqlBuilder.DELETE_FROM;
import static org.apache.ibatis.jdbc.SqlBuilder.INSERT_INTO;
import static org.apache.ibatis.jdbc.SqlBuilder.SET;
import static org.apache.ibatis.jdbc.SqlBuilder.SQL;
import static org.apache.ibatis.jdbc.SqlBuilder.UPDATE;
import static org.apache.ibatis.jdbc.SqlBuilder.VALUES;
import static org.apache.ibatis.jdbc.SqlBuilder.WHERE;

import org.apache.ibatis.jdbc.SelectBuilder;

import com.core.traininig.entity.Member;
import com.core.traininig.entity.Task;

/**
 * @author aron.tang
 */
public class EntityProvider {

    public static String getInsertSql(final Task task) {
        BEGIN();
        INSERT_INTO("TASK");
        VALUES("TASK_ID", "#{taskId,jdbcType=INTEGER}");
        VALUES("MEMBER_ID", "#{memberId,jdbcType=INTEGER}");
        VALUES("CONTENT", "#{content,jdbcType=VARCHAR}");
        VALUES("DUE_DATE", "#{dueDate,jdbcType=DATE}");
        return SQL();
    }

    public static String getUpdateSql(final Member member) {
        BEGIN();
        UPDATE("MEMBER");
        SET("FIRST_NAME=#{firstName,jdbcType=VARCHAR}");
        SET("LAST_NAME=#{lastName,jdbcType=VARCHAR}");
        SET("ADDRESS=#{address,jdbcType=VARCHAR}");
        SET("PHONE=#{phone,jdbcType=VARCHAR}");
        WHERE("MEMBER_ID=#{memberId,jdbcType=INTEGER}");
        return SQL();
    }

    public static String getSelectSql(final int memberId) {
        SelectBuilder.BEGIN();
        SelectBuilder.SELECT("MEMBER_ID AS memberId, FIRST_NAME AS firstName, LAST_NAME AS lastName" +
                ", ADDRESS AS address, PHONE AS phone ");
        SelectBuilder.FROM("MEMBER");
        SelectBuilder.WHERE("MEMBER_ID=#{memberId,jdbcType=INTEGER}");
        return SelectBuilder.SQL();
    }

    public static String getDelSql(final int taskId) {
        BEGIN();
        DELETE_FROM("TASK");
        WHERE("TASK_ID=#{#taskId,jdbcType=INTEGER}");
        return SQL();

    }

}


MemberMapper:
// Copyright (c) 1998-2012 Core Solutions Limited. All rights reserved.

package com.core.traininig.mybatisquiz;

import java.util.List;

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

   @InsertProvider(method = "getInsertSql", type = EntityProvider.class)
   void createTask(Task task);

   @UpdateProvider(method = "getUpdateSql", type = EntityProvider.class)
   void updateMember(Member member);

   @SelectProvider(method = "getSelectSql", type = EntityProvider.class)
   Member getMemberById(int memberId);

   @DeleteProvider(method = "getDelSql", type = EntityProvider.class)
   void delTask(int taskId);

}


其中@InsertProvider,@UpdateProvider,@SelectProvide, @DeleteProvider这几个注解告诉mapper sql将会从哪个类的哪个方法动态生成.

测试类TestProvider:
// Copyright (c) 1998-2013 Core Solutions Limited. All rights reserved.

package com.core.traininig.mybatisquiz;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

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 TestProvider {

    private static SqlSessionFactory sqlSessionFactory;

    public static void main(final String[] args) throws IOException {
        //testCreateTask();
        //testUpdateMember();
        testGetMemberById(4);
        // testDelTask(10);
    }

    /**
     * @param i
     * @throws IOException
     */
    private static void testDelTask(final int id) throws IOException {
        final SqlSession session = getSession();
        final MemberMapper m = session.getMapper(MemberMapper.class);
        m.delTask(id);
        System.out.println("succeed to cancel task.");
        session.commit();
    }

    /**
     * @param i
     * @throws IOException
     */
    private static void testGetMemberById(final int id) throws IOException {
        final SqlSession session = getSession();
        final Member m = session.getMapper(MemberMapper.class).getMemberById(id);
        System.out.println(m.getFirstName() + "." + m.getLastName());
    }

    /**
     * @throws IOException
     *
     */
    private static void testUpdateMember() throws IOException {
        final Member m = new Member();
        m.setMemberId(4);
        m.setFirstName("dickson");
        m.setLastName("wong");
        m.setAddress("usa");
        m.setPhone("376529081");
        final SqlSession session = getSession();
        final MemberMapper mapper = session.getMapper(MemberMapper.class);
        mapper.updateMember(m);
        System.out.println("succeed to update member " + m);
        session.commit();
        session.close();
    }


    private static SqlSession getSession() throws IOException {
        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);
        final SqlSession session = sqlSessionFactory.openSession();
        return session;

    }


    private static void closeSession() {
        final SqlSession session = sqlSessionFactory.openSession();
        if (session != null) {
            session.close();
        }
    }

    private static void testCreateTask() throws IOException {
        final Task t = new Task();
        t.setTaskId(10);
        t.setMemberId(4);
        t.setContent("doing mybatis test1");
        t.setDueDate(new Date());
        final SqlSession session = getSession();
        final MemberMapper m = session.getMapper(MemberMapper.class);
        m.createTask(t);
        session.commit();
        System.out.println("create Task successfully.");
    }

}

你可能感兴趣的:(java,sql)