第一章:Mybatis开发环境搭建,集成mysql数据库

一)开发前准备

mybatis-3.4.6.jar

mysql-connector-java-5.1.34-bin.jar

说明:在本章末尾有源码下载地址,里面已包含jar

二)Mybatis开发环境搭建

1) 创建一个Dynamic Web Project,名称为:xm-mybatis-one,项目结构图如下:

2)创建员工实体文件EmployeeEntity.java

package com.xm.mybatis.entity;

/**
 * 员工表 entity
 * @author ouyangjun
 *
 */
public class EmployeeEntity {
	
	private Integer empId;
	
	private String empName;
	
	private String empNO;
	
	private Long createDate;

	public Integer getEmpId() {
		return empId;
	}

	public void setEmpId(Integer empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpNO() {
		return empNO;
	}

	public void setEmpNO(String empNO) {
		this.empNO = empNO;
	}

	public Long getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Long createDate) {
		this.createDate = createDate;
	}
	
}

3)创建员工实体映射文件EmployeeEntity.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xm.mybatis.dao.EmployeeDAO">

	<insert id="addEmployee">
		insert into employee(emp_id,emp_name,emp_no,create_date)
		values(#{empId}, #{empName}, #{empNO}, #{createDate})
	</insert>
	
	<select id="getEmployeeByEmpId" parameterType="java.lang.String" resultType="employeeEntity">
		select 
			emp_id as empId,
			emp_name as empName,
			emp_no as empNO,
			create_date as createDate
		 from employee where emp_id = #{empId}
	</select>
	
	<update id="updateEmployee">
		
	</update>
	
	<!-- 
		foreach元素的属性主要有 item,index,collection,open,separator,close。
		item表示集合中每一个元素进行迭代时的别名,
		index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
		open表示该语句以什么开始,
		separator表示在每次进行迭代之间以什么符号作为分隔 符,
		close表示以什么结束。
		collection
			1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list, parameterType="java.util.List"
			2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array, parameterType="java.util.ArrayList"
			3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可, parameterType="java.util.HashMap"
	 -->
	<delete id="deleteEmployeeEntityByEmpId" parameterType="java.util.ArrayList">
		delete from employee where 1=1
		and emp_Id in 
		<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</delete>
  	
</mapper>

4)创建员工接口文件EmployeeDAO.java

package com.xm.mybatis.dao;

import com.xm.mybatis.entity.EmployeeEntity;

public interface EmployeeDAO {

	/**
	 * 根据empId获取员工信息
	 * @param empId
	 * @return
	 */
	EmployeeEntity getEmployeeByEmpId(String empId);
	
	/**
	 * 添加员工
	 * @param entity
	 * @return
	 */
	int addEmployee(EmployeeEntity entity);
	
	/**
	 * 根据empId修改用户信息
	 * @param empId
	 * @return
	 */
	int updateEmployee(EmployeeEntity entity);
	
	/**
	 * 根据empId删除用户
	 */
	int deleteEmployeeEntityByEmpId(String[] empIds);
	
}

5)创建mybatis核心配置文件mybatis.cfg.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>
	
	<!-- 给全限定类名命个别名,减少xml实体类引用代码 -->
	<typeAliases>
		<!-- 方式一:给单个实体类名一个别名,在对应的xml中引用别名即可
		<typeAlias alias="employeeEntity" type="com.xm.mybatis.entity.EmployeeEntity"></typeAlias>
		-->
		
		<!-- 方式二:当有多个实体类的时候,引用实体类包名,实体类别人首字母默认小写(如: employeeEntity)。如果实体类上有注解别名,以注解为准! -->
		<package name="com.xm.mybatis.entity"/>
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<!-- type="JDBC" 表示使用JDBC的提交和回滚管理事务 -->
			<transactionManager type="JDBC" />
			
			<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
			<!-- POOLED 表示支持JDBC数据源连接池 -->
			<!-- UNPOOLED 表示不支持数据源连接池 -->
			<!-- JNDI 表示支持外部数据源连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/xm" />
				<property name="username" value="root" />
				<property name="password" value="admin" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="com/xm/mybatis/entity/EmployeeEntity.xml" />
	</mappers>
	
</configuration>

6)创建获取SqlSessionFactory的工具类SessionUtils.java。通过单列模式实现。

package com.xm.mybatis.utils;

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

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

public class SessionUtils {
	
	/**
	 * 内部类单列模式实现读取mybatis配置文件
	 * @author ouyangjun
	 */
	private static class LasyHolder {
		
		private static Reader READER = getReader();
		
		public static Reader getReader() {
			try {
				System.out.println("==>读取mybatis.cfg.xml文件中的配置!");
				// 读取mybatis配置文件
				return Resources.getResourceAsReader("mybatis.cfg.xml");
			} catch (IOException e) {
				System.out.println("==>读取mybatis.cfg.xml文件中的配置错误 error!");
				e.printStackTrace();
			}
			return null;
		}
	}
	
	/**
	 * 获取配置文件对象
	 * @return
	 */
	public static Reader getReader() {
		return LasyHolder.READER;
	}
	
	/**
	 * 线程本地配置声明
	 */
	public static ThreadLocal<SqlSessionFactory> threadLocal = new ThreadLocal<SqlSessionFactory>();
	
	/**
	 * ThreadLocal获取SqlSessionFactory
	 * @return
	 */
	public static SqlSessionFactory getSqlSessionFactory() {
		// 获取sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = threadLocal.get();
		
		System.out.println("sqlSessionFactory: " + sqlSessionFactory);
		if (sqlSessionFactory == null) {
			System.out.println("sqlSessionFactory is null 重新获取SqlSessionFactory!");
			// 读取mybatis配置文件
			Reader reader = SessionUtils.getReader();
			
			// 重新创建SqlSessionFactory
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
			// 把sqlSessionFactory添加到ThreadLocal中
			threadLocal.set(sqlSessionFactory);
		}
		
		// 返回
		return sqlSessionFactory;
	}

}

7)添加员工新增测试类AddEmployeeTest.java,执行该方法之后可自行到mysql数据库查看。

package com.xm.mybatis.test;

import java.util.Date;

import org.apache.ibatis.session.SqlSession;

import com.xm.mybatis.dao.EmployeeDAO;
import com.xm.mybatis.entity.EmployeeEntity;
import com.xm.mybatis.utils.SessionUtils;

public class AddEmployeeTest {

	public static void main(String[] args) {
		// 获取SqlSession
		SqlSession sqlSession = null;
		
		try {
			sqlSession = SessionUtils.getSqlSessionFactory().openSession();
			
			// 初始化接口
			EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
			EmployeeEntity emp = new EmployeeEntity();
			emp.setEmpId(100000);
			emp.setEmpName("ouyangjun");
			emp.setEmpNO("333333");
			emp.setCreateDate(new Date().getTime());
			
			// 持久化
			employeeDAO.addEmployee(emp);
			
			emp = new EmployeeEntity();
			emp.setEmpId(200000);
			emp.setEmpName("xm");
			emp.setEmpNO("888888");
			emp.setCreateDate(new Date().getTime());
			
			// 持久化
			employeeDAO.addEmployee(emp);
			
			// 提交事务
			sqlSession.commit();
			
			System.out.println("==>员工数据持久化成功!");
		} catch (Exception e){
			e.printStackTrace();
			sqlSession.rollback();
			
			System.out.println("==>员工数据持久化失败!");
		} finally {
			sqlSession.close();
			
			System.out.println("==>事务关闭!");
		}
	}

}

8)添加员工查询测试类GetEmployeeTest.java

package com.xm.mybatis.test;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import com.xm.mybatis.dao.EmployeeDAO;
import com.xm.mybatis.entity.EmployeeEntity;
import com.xm.mybatis.utils.SessionUtils;

public class GetEmployeeTest {

	public static void main(String[] args) throws IOException {
		
		// 获取SqlSession
		SqlSession sqlSession = SessionUtils.getSqlSessionFactory().openSession();
		
		// 初始化接口
		EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
		
		EmployeeEntity entity = employeeDAO.getEmployeeByEmpId("100000");
		if(entity!=null){
			System.out.println(entity.getEmpId()+" "+entity.getEmpName()+" "+entity.getEmpNO());
		} else {
			System.out.println("根据empId未查询到数据!");
		}
		
		System.out.println("----------测试SqlSessionFactory单列----------");
		
		sqlSession = SessionUtils.getSqlSessionFactory().openSession();
		// 初始化接口
		employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
		entity = employeeDAO.getEmployeeByEmpId("100000");
		if(entity!=null){
			System.out.println(entity.getEmpId()+" "+entity.getEmpName()+" "+entity.getEmpNO());
		} else {
			System.out.println("根据empId未查询到数据!");
		}
		
		sqlSession.close();
	}

}

查询效果图如下:

9)添加员工删除测试类DeleteEmployeeTest.java

package com.xm.mybatis.test;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import com.xm.mybatis.dao.EmployeeDAO;
import com.xm.mybatis.utils.SessionUtils;

public class DeleteEmployeeTest {

	public static void main(String[] args) throws IOException {
		
		// 获取SqlSession
		SqlSession sqlSession = null;
		
		try {
			sqlSession = SessionUtils.getSqlSessionFactory().openSession();
			
			// 初始化接口
			EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
			String[] empIds = {"100000","200000"};
			employeeDAO.deleteEmployeeEntityByEmpId(empIds);
			
			sqlSession.commit();
			
			System.out.println("==>员工数据删除成功!");
		} catch (Exception e){
			e.printStackTrace();
			sqlSession.rollback();
			
			System.out.println("==>员工数据删除失败!");
		} finally {
			sqlSession.close();
			
			System.out.println("==>事务关闭!");
		}
	}

}

本章完结,待续!

源码下载地址: https://gitee.com/ouyangjun_xm/mybatis/attach_files下xm-mybatis-one.rar压缩包

                      码云账户: [email protected]     密码: [email protected]

                      请勿恶意操作,谢谢!

本文说明:该文章属于原创,如需转载,请标明文章转载来源

猜你喜欢

转载自blog.csdn.net/p812438109/article/details/81584946