mybatis_day01_入门

概述

介绍

MyBatis 本是apache的一个开源项目iBatis

2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis

2013年11月迁移到Github

概念

MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装

Mybatis通过xml或注解的方式进行开发

JDBC编程问题总结

package com.itheima.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTest {

	public static void main(String[] args) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			// 加载数据库驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 通过驱动管理类获取数据库链接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
					"root", "root");
			// 定义sql语句 ?表示占位符
			String sql = "select * from user where username = ?";
			// 获取预处理statement
			preparedStatement = connection.prepareStatement(sql);
			// 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
			preparedStatement.setString(1, "王五");
			// 向数据库发出sql执行查询,查询出结果集
			resultSet = preparedStatement.executeQuery();
			// 遍历查询结果集
			while (resultSet.next()) {
				System.out.println(resultSet.getString("id") + "  " + resultSet.getString("username"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
  • 数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。如果使用数据库连接池可解决此问题。
  • Sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变化的可能较大,sql变动需要改变java代码。
  • 使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能多也可能少,修改sql还要修改代码,系统不易维护。
  • 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便

mybatis框架结构

mybatis_day01_入门_第1张图片

 

  • mybatis配置
    • SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。
    • mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。
  • 通过mybatis环境等配置信息构造SqlSessionFactory,即会话工厂
  • 由会话工厂创建sqlSession,即会话,操作数据库需要通过sqlSession进行
  • mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器
  • Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id
  • Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数
  • Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程

入门案例

下载

https://github.com/mybatis/mybatis-3/releases

mybatis_day01_入门_第2张图片

环境搭建

数据库和表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单id',
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

 

创建java工程

mybatis_day01_入门_第3张图片

导入jar包

mybatis_day01_入门_第4张图片

核心配置文件

在工程下创建一个资源文件夹,名字为config,创建核心配置文件SqlMapConfig.xml



	

	
	
		
			
			
			
			
				
				
				
				
			
		
	
	
	
	
		
	

日志文件

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

POJO

package com.itheima.pojo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址

	public Integer getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
				+ address + "]";
	}

}

映射文件






	
	
	
	
	
	
	
	
		
		
		
		
		
		
			SELECT LAST_INSERT_ID()
		
		insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
	
	
	
	
		update user set username = #{username} where id=#{id}
	
	
	
	
		delete from user where id=#{id}
	
	

package com.itheima.test;

import static org.junit.Assert.*;

import java.io.InputStream;
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 org.junit.Before;
import org.junit.Test;

import com.itheima.pojo.User;

public class MybatisTest {

	private SqlSessionFactory sqlSessionFactory;
	@Before
	public void init() throws Exception {
		String resource = "SqlMapConfig.xml";
		//读取配置文件
		InputStream inputStream = Resources.getResourceAsStream(resource);
		//创建工厂
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	@Test
	public void selelctUserById() throws Exception {
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//参数说明:1.指定要执行的sql语句,2.SQL语句中的占位符
		User user = sqlSession.selectOne("test.selectUserById", 10);
		
		System.err.println(user);
		
		sqlSession.close();
	}
	
	@Test
	public void selectUserByUsername() throws Exception {
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//参数说明:1.指定要执行的sql语句,2.SQL语句中的占位符
		List list = sqlSession.selectList("test.selectUserByUsername", "小");
		
		for (User user : list) {
			System.err.println(user);
		}
		sqlSession.close();
	}
	
	@Test
	public void saveUser() throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		User user = new User();
		user.setUsername("边江");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("北京");
		sqlSession.insert("test.saveUser",user);
		
		sqlSession.commit();
		sqlSession.close();
	}
	
	@Test
	public void updateUserById() throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		User user = new User();
		user.setId(26);
		user.setUsername("阿杰");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("北京");
		sqlSession.insert("test.updateUserById",user);
		
		sqlSession.commit();
		sqlSession.close();
	}
	
	@Test
	public void deleteUserById() throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		sqlSession.delete("test.deleteUserById",26);
		
		sqlSession.commit();
		sqlSession.close();
	}

}

 

你可能感兴趣的:(SSM框架)