MyBatis(二)第一个Mybatis项目

下载源码请添加微信号:flx_tow_target

项目下载路径:http://pan.baidu.com/s/1pLhvORT

一、学习前言

好记性不如烂笔头,现在虽然已经对Mybatis使用一段时间了,不过喝水不要忘了挖井人,要是学好Mybatis框架就得的从搭建环境说起,下面我就开始讲解环境的搭建以及第一个项目的实战

二、环境搭建

 1、JAR包,mysql;可视化工具Navicat Premiumk。

            
            JAR包包含:mybatis-3.4.5.jar
    mysql-connector-java-5.1.26-bin.jar
    log4j-1.2.17.jar

  2、项目结构图





3、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>
    <!-- 配置数据源 -->
	<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://***.**.**.***/mystock" />
				<property name="username" value="********" />
				<property name="password" value="********" />
			</dataSource>
		</environment>
	</environments>
	<!-- 引用配置文件 -->
	<mappers>
		<mapper resource="com/flx/config/Mapper.xml" />
	</mappers> 
</configuration>

4、读取配置文件类 SqlSessionUtils.java

package com.flx.utils;

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;

/**
 * 读取Mybatis数据源文件
 * @author Administrator
 * @2017-9-28下午11:57:33
 *
 */

public class SqlSessionUtils {

	/**
	 * 功能:获取sqlSession
	 * @author FuLX 2017-9-23
	 */
	public static SqlSession getSqlSession() throws IOException {
		// 1、通过配置文件获取链接数据库的信息
		Reader config = Resources.getResourceAsReader("mybatis-config.xml");
		// 2、通过一个配置文件信息获创建SqlSessionFactory
		SqlSessionFactory build = new SqlSessionFactoryBuilder().build(config);
		// 3、通过SqlSessionFactory打开一个会话
		SqlSession sqlSession = build.openSession();

		return sqlSession;
	}

}

5、SQL配置文件  Mapper.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="Message">
<resultMap type="com.flx.dto.Message" id="MessageResult">
	<id column="id" jdbcType="INTEGER" property="id"/>
	<result column="username" jdbcType="VARCHAR" property="username"/>
	<result column="password" jdbcType="VARCHAR" property="password"/>
</resultMap>

<!-- 
select 元素有很多种配置
id:命名空间中唯一标识,也可以被用来引用这条语句
parameterType:将会传进这条语句中的参数类的完全限制名或者别名
resultMap:引用外部的resultMap
resultType:从这条语句中但会期望的完全限制名或者别名,和resultMap不能同时使用

ONGL:是一种特殊的表达式,它可以支持JAVA语法
  "":需要进行在XMl中需要进行转义
mybatis:
	#{sex}:是在mybatis中处理的,在读取到#好时候会替换掉
 -->
<select id="getMessageList" parameterType="com.flx.dto.Message" resultMap="MessageResult">
  SELECT ID,USERNAME,PASSWORD FROM MESSAGES  WHERE 1 = 1
	  <if test="sex != null and !"".equals(sex.trim())">
	  	and sex = #{sex}
	  </if>
	   <if test="username != null and !"".equals(username.trim())">
	  	and username = #{username}
	  </if>
	  <if test="password != null and !"".equals(password.trim())">
	  	and password = #{password}
	  </if>
</select>

</mapper>
对应的实体类
package com.flx.dto;

public class Message {
	private int id;
	private String username;
	private String password;
	private String sex;
	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;
	}
	
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Message [id=" + id + ", username=" + username + ", password="
				+ password + "]";
	}

}

6、DAO层

package com.flx.dao;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.flx.dto.Message;
import com.flx.utils.SqlSessionUtils;

public class MessageDAO {
	

	/**
	 * select 语句进行查询
	 * @author FuLX 2017-9-23
	 */
	public List<Message> getMessageList() {
		SqlSession sqlSession = null;
		List<Message> messageList = null;
		try {
			Message message = new Message();
//			message.setUsername("flx01");
			message.setPassword("111");
			sqlSession = SqlSessionUtils.getSqlSession();//获取sqlSession
			messageList = sqlSession.selectList("Message.getMessageList",message);//调用查询
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
		return messageList;
	}
	
	/**
	 * insert 语句案例
	 * @author FuLX 2017-9-23
	 */
	public void insertData(Object object){
		SqlSession sqlSession  = null;
		try {
			//1、获取SqlSession对象
			sqlSession = SqlSessionUtils.getSqlSession();
			//2、对数据库进行操作
			Message message = new Message();
			message.setUsername("estar");
			message.setPassword("8888");
			sqlSession.insert("",message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//3、对sqlSession 进行关闭
			if(sqlSession != null){
				sqlSession.close();
			}
		}
		
	}

	public static void main(String[] args) {
		List<Message> messageList = new MessageDAO().getMessageList();
		for (Message message : messageList) {
			System.out.println(message.getId()+"-"+message.getUsername()+"-"+message.getPassword());
		}
	}
}

7、日志文件log4j.properties


注意:配置为DEBUG才能输出SQL语句以及参数
#针对于整个工程下面  XING属于自定义的,定义为DEBUG后,级别是最小的,比它级别高的都输出来,INFO,EREO..
#rootLogger  总工程的,
log4j.rootLogger=DEBUG,XING
#log4j.appender属于关键字,不能动,XING跟上面的一致
log4j.appender.XING=org.apache.log4j.ConsoleAppender
#布局,按照自己的想法输出
log4j.appender.XING.layout=org.apache.log4j.PatternLayout
#输出日志格式,
#d输出日志的时间
#t输出日志的所在的线程
#-5输出字符为5位,在有‘-’号在右边补齐
#p输出日志的级别,比如:debug,info等等,看看属于哪一个
#%c指的是输出的类所在的路径
#%m输出你添加的信息
#%n换行
log4j.appender.XING.layout.ConversionPattern=%d[%t]%-5p [%c] - %m%n

#log4j.logger是固定的,不能动
#org.apache自己定的包,例如:com.flx.estar,那个这个包下面就不会输出DEBUG级别了,只有INFO及以上
log4j.logger.org.apache = INFO

8、控制台输出日志

2017-09-28 23:28:08,003[main]DEBUG [Message.getMessageList] - ==>  Preparing: select id,username,password from messages WHERE password = ? 
2017-09-28 23:28:08,080[main]DEBUG [Message.getMessageList] - ==> Parameters: 111(String)
2017-09-28 23:28:08,126[main]DEBUG [Message.getMessageList] - <==      Total: 1
1-flx01-111

9、为什么配置DEBUG就会输出配置文件呢?

答:原始是在Mybatis源码中有做处理;对应的class:org.apache.ibatis.logging.jdbc.ConnectionLogger.class




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值