cn.songxinqiang.study.mybatis.test.HelloMyBatis.java Source code

Java tutorial

Introduction

Here is the source code for cn.songxinqiang.study.mybatis.test.HelloMyBatis.java

Source

/**
 * <pre>
 * Copyright 2014,2015 sxq(songxinqiang@vip.qq.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </pre>
 */
/*
 * 20151126--?11:28:35
 * sxq(songxinqiang@vip.qq.com)
 */
package cn.songxinqiang.study.mybatis.test;

import java.io.IOException;
import java.io.Reader;
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 cn.songxinqiang.study.mybatis.model.User;

/**
 *
 * <p>
 * ?, , ????.
 * </p>
 *
 * @author sxq-20151126
 *
 */
public class HelloMyBatis {

    public static void main(String[] args) throws IOException {
        // mybatis?
        String resource = "conf.xml";
        // mybatis??
        // InputStream is = HelloMyBatis.class.getClassLoader().getResourceAsStream(resource);
        // sqlSession
        // SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        // MyBatis??Resourcesmybatis??
        Reader reader = Resources.getResourceAsReader(resource);
        // sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        // sqlsqlSession
        SqlSession session = sessionFactory.openSession();
        /**
         * sql
         * mapper.userMapperuserMapper.xmlmappernamespace
         * getUserselectidselectid??SQL
         */
        String statement = "mapper.userMapper.getUser";// sql
        // usersql
        User user = session.selectOne(statement, 2);
        System.out.println(user);

        statement = "mapper.userMapper.listUser";// sql
        List<User> users = session.selectList(statement);
        System.out.println(users);
    }
}