MyBatis入门

一、MyBatis简介
MyBatis本是Apache的一个开源项目iBatis,是一个基Java的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

二、MyBaits实例
2.1  开发环境准备(数据库以MySql为例)
1.创建一个Web Project或者Java Project

2.添加相应的jar包

  【mybatis-3.4.5.jar】下载地址:https://github.com/mybatis/mybatis-3/releases

    【mysql.jar】


3.创建数据库与表
2.2  使用MyBatis进行数据库操作
1.添加配置文件Configuration.xml:

    Configuration.xml的内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2016 the original author or authors.

       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.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases>
 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="Admin888"/>
      </dataSource>
    </environment>
  </environments>

</configuration>
2.编写与数据库表所对应的实体类:

    UserInfo.java代码如下:

package com.mybatisdemo.bean;

public class UserInfo {
	private int id;
	private String username;
	private String password;

	public UserInfo() {
	}

	public UserInfo(int id, String username, String password) {
		this.id = id;
		this.username = username;
		this.password = password;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	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;
	}
}
3.创建操作数据库表UserInfo的映射文件UserInfo.xml:

UserInfo.xml的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2016 the original author or authors.

       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.

-->
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为mapper指定唯一namespace -->
<mapper namespace="Userinfo">

  <!-- 配置返回结果集类型,赋予唯一id,type表示与结果集类型所对应的bean对象 -->
  <resultMap type="com.mybatisdemo.bean.UserInfo" id="UserInfoResult">
    <!-- id为主键,result为表中的普通字段,column为bean中的属性,property为对于的表中的字段,
        jdbcType为数据类型 -->
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="username" jdbcType="VARCHAR" property="username"/>
    <result column="password" jdbcType="VARCHAR" property="password"/>
  </resultMap>
</mapper>
4.在Configuration.xml中注册映射文件UserInfo.xml:

    在Configuration.xml中的<configuration></configuration>节点中添加一段代码:

  <!-- resource对应映射文件UserInfo.xml -->
  <mappers>
    <mapper resource="com/mybatisdemo/config/Userinfo.xml"/>
  </mappers>
5.创建获得sqlSession的工具类:

    GetSqlSession.java代码如下:

package com.mybatisdemo.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class GetSqlSession {
	public SqlSession openSqlSession() throws IOException{
		//声明Configuration.xml的路径为path
		String path = "com/mybatisdemo/config/Configuration.xml";
		//通过配置文件来获得数据库连接
		Reader reader = Resources.getResourceAsReader(path);
		//通过配置信息构建一个SqlSessionFactory
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		//通过SqlSessionFactory打开一个数据库会话
		SqlSession sqlSession = sessionFactory.openSession();
		return sqlSession;
	}
}
6.往UserInfo.xml中<mapper></mapper>节点下添加代码:

<!-- id为此select赋予id,resultMap表示SQL语句执行后返回的结果集类型,
  		与resultMap的id对应,select标签里为要执行的SQL语句 -->
<select id="selectAll" resultMap="UserInfoResult">
  SELECT ID,USERNAME,PASSWORD FROM USERINFO
</select>
7.创建数据库访问类:

    UserInfoDao.java代码如下:

package com.mybatisdemo.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mybatisdemo.bean.UserInfo;
import com.mybatisdemo.util.GetSqlSession;

public class UserInfoDao {
	public List<UserInfo> selectAll(){
		//获得sqlSession获得类
		GetSqlSession getSqlSession = new GetSqlSession();
		//声明sqlSession
		SqlSession sqlSession = null;
		//声明接收查询数据的list集合
		List<UserInfo> userInfo = new ArrayList<UserInfo>();
		try {
			//打开SqlSession
			sqlSession = getSqlSession.openSqlSession();
			/*
			 * 执行SQL语句,Userinfo为UserInfo.xml中mapper的namespace,
			 * selectAll为要执行的SQL语句对应的select标签ID
			 */
			userInfo = sqlSession.selectList("Userinfo.selectAll");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			//关闭SqlSession
			if(sqlSession != null){
				sqlSession.close();
			}
		}
		return userInfo;
	}
}
8.编写测试类实现全表查询:

    Test.java代码如下:

package com.mybatisdemo.util;

import java.util.List;

import com.mybatisdemo.bean.UserInfo;
import com.mybatisdemo.dao.UserInfoDao;

public class Test {
	public static void main(String[] args) {
		UserInfoDao uid = new UserInfoDao();
		List<UserInfo> userInfo = uid.selectAll();
		for(UserInfo userinfo : userInfo){
			System.out.println("id: "+userinfo.getId()+"    username: "+userinfo.getUsername()+"    password: "+userinfo.getPassword());
		}
	}
}
    执行结果:


    数据库里面的内容就成功通过MyBatis查询出来啦!

2.3  源码下载

    http://download.youkuaiyun.com/download/qw9326/10208070









评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值