mybatis连接mysql数据库实现的jdbc功能

最近公司项目要使用myBatis,自己以前没有接触过,就在网上找到了一些资料研究了些。初步做出了基于myBatis连接mysql数据库的jdbc实现的功能。

employee.java

package com.org.position.model;

public class employee {
	private int     employeeId;// 员工id
	private String  employeeName; //员工姓名
	private String  employeeSax; //员工性别
	private String  employeePost; //员工职务
	private String  employeeDepartment; //员工所在部门

	public int getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	public String getEmployeeName() {
		return employeeName;
	}
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}
	public String getEmployeeSax() {
		return employeeSax;
	}
	public void setEmployeeSax(String employeeSax) {
		this.employeeSax = employeeSax;
	}
	public String getEmployeePost() {
		return employeePost;
	}
	public void setEmployeePost(String employeePost) {
		this.employeePost = employeePost;
	}
	public String getEmployeeDepartment() {
		return employeeDepartment;
	}
	public void setEmployeeDepartment(String employeeDepartment) {
		this.employeeDepartment = employeeDepartment;
	}

}

 employeeDao.java

package com.org.position.dao;

import java.util.List;

import com.org.position.model.employee;

public interface employeeDao {
   public int countAll();
   public employee findEnterprise(int employeeId);
   public int insertEnterprise(employee emp);
   public int deleteEnterprise(int employeeId);
   public List<employee> getAllEnterprise();
   public int updateEnterprise(employee emp );
   public List<employee> findEnterpriseByExampleIf(employee emp);

}

employeeDaoimpal.java

package com.org.position.dao.impal;

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 com.org.position.dao.employeeDao;
import com.org.position.model.employee;

public class employeeDaoimpal implements employeeDao {

	@Override
	public int countAll() {
		String resource="mybaits-config.xml";
		Reader reader=null;
		SqlSessionFactory  ssf=null;
		SqlSession session=null;
		int iCount=0;
		try {
			reader= Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
			ssf=builder.build(reader);
			session=ssf.openSession();
			iCount=session.selectOne("com.org.position.dao.employeeDao.countAll");
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return iCount;
	}

	@Override
	public employee findEnterprise(int employeeId) {
		String resource="mybaits-config.xml";
		Reader reader=null;
		SqlSessionFactory  ssf=null;
		SqlSession session=null;
		employee  emp=null;
		try {
			reader = Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			ssf = builder.build(reader);
			session=ssf.openSession();
			employeeDao empdao=session.getMapper(employeeDao.class);
			emp=empdao.findEnterprise(employeeId);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			session.close();
		}

		return emp;
	}

	@Override
	public int insertEnterprise(employee emp) {
		String resource="mybaits-config.xml";
		Reader reader=null;
		SqlSessionFactory  ssf=null;
		SqlSession session=null;
		int count=0;
		try {
			reader = Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			ssf = builder.build(reader);
			session=ssf.openSession();
			count=session.insert("com.org.position.dao.employeeDao.insertEnterprise",emp);
			session.commit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return count;
	}

	@Override
	public int deleteEnterprise(int employeeId) {
		String resource="mybaits-config.xml";
		Reader reader = null;
		SqlSessionFactory ssf=null;
		SqlSession session=null;
		int iCount = 0;
		try {
			reader = Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			ssf = builder.build(reader);
			session=ssf.openSession();
			iCount=session.delete("com.org.position.dao.employeeDao.deleteEnterprise", employeeId);
			session.commit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			session.close();
		}

		return iCount;
	}

	@Override
	public List<employee> getAllEnterprise() {
		String resource="mybaits-config.xml";
		Reader reader = null;
		SqlSessionFactory ssf=null;
		SqlSession session=null;
		List<employee> emps = null;
		try {
			reader = Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			ssf = builder.build(reader);
			session=ssf.openSession();
			emps=session.selectList("com.org.position.dao.employeeDao.getAllEnterprise");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			session.close();
		}
		return emps;
	}

	@Override
	public int updateEnterprise(employee emp) {
		String resource="mybaits-config.xml";
		Reader reader = null;
		SqlSessionFactory ssf=null;
		SqlSession session=null;
		int iCount = 0;
			try {
				reader = Resources.getResourceAsReader(resource);
				SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

				ssf = builder.build(reader);
				session=ssf.openSession();
				iCount=session.delete("com.org.position.dao.employeeDao.updateEnterprise",emp);
				session.commit();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				session.close();
			}

		return iCount;
	}

	@Override
	public List<employee> findEnterpriseByExampleIf(employee emp) {
		String resource="mybatis-config.xml";
		Reader reader = null;
		SqlSessionFactory ssf=null;
		SqlSession session=null;
		List<employee> emps = null;
		try {
			reader = Resources.getResourceAsReader(resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			ssf = builder.build(reader);
			session=ssf.openSession();
			emps=session.selectList("com.org.position.dao.employeeDao.findEnterpriseByExampleIf",emp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			session.close();
		}

		return emps;
	}

}

 employeeDaoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper  namespace="com.org.position.dao.employeeDao">
  <resultMap type="com.org.position.model.employee" id="empResultMap">
    <id property="employeeId" column="employeeId"/>
    <result property="employeeName" column="employeeName" />
    <result property="employeeSax" column="employeeSax"/>
    <result property="employeePost" column="employeePost"/>
     <result property="employeeDepartment" column="employeeDepartment"/>
  </resultMap>
   <select id="findEnterpriseByExampleIf" parameterType="com.org.position.model.employee"  resultMap="empResultMap">
      select * from employee where 1=1
     <if test="employeed !=null">
         and employeeId=#{employeeId}
     </if>
       <if test="employeename!=null">
         and employeeName=#{employeeName}
       </if>
        <if test="employeesax! =null">
         and employeeSax=#{employeeSax}
        </if>
        <if test="employeepost!=null">
         and employeePost=#{employeePost}
        </if>
        <if test="employeedepartment! =null">
         and  employeeDepartment=#{employeeDepartment}
        </if>
   </select>

   <select id="countAll"  resultType="int">
       select count(*) from t_employee
   </select>
  <!--   根据id查询对应的数据信息 -->
   <select id="findEnterprise" parameterType="int" resultType="com.org.position.model.employee">
     select * from t_employee where employeeId=#{employeeId}
   </select>
    <!--    查询所有 数据 -->
   <select id="getAllEnterprise" resultType="com.org.position.model.employee">
      select * from t_employee
   </select>
        <!-- 添加数据信息 -->
   <insert id="insertEnterprise" parameterType="com.org.position.model.employee">
        insert into  t_employee(employeeId,employeeName,employeeSax,employeePost,employeeDepartment)
        values (#{employeeId},#{employeeName},#{employeeSax},#{employeePost},#{employeeDepartment})
   </insert>
        <!-- 更新数据信息 -->
   <update id="updateEnterprise" parameterType="com.org.position.model.employee">
     update t_employee set employeeName=#{employeeName},employeeSax=#{employeeSax},employeePost=#{employeePost},employeeDepartment=#{employeeDepartment}
     where employeeId=#{employeeId}
   </update>
    <!-- 删除数据信息 -->
   <delete id="deleteEnterprise" parameterType="com.org.position.model.employee">
    delete from t_employee where employeeId=#{employeeId}

   </delete>
</mapper>

 mybaits-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"></transactionManager>
     <dataSource type="POOLED">
     <property name="driver" value="com.mysql.jdbc.Driver"/>
     <property name="url" value="jdbc:mysql://localhost:3306/test"/>
	 <property name="username" value="root"/>
	 <property name="password" value="mysql"/>
     </dataSource>
     </environment>
   </environments>
  <mappers>
    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  </mappers>
</configuration>

 employeeTest.java

package com.org.position.test;

import java.util.List;

import com.org.position.dao.employeeDao;
import com.org.position.dao.impal.employeeDaoimpal;
import com.org.position.model.employee;

public class employeeTest {

	public static void testAddEmp(){
    	employee emp=new employee();
    	employeeDao dao=new employeeDaoimpal();
    	emp.setEmployeeId(11);
    	emp.setEmployeeName("爽");
    	emp.setEmployeeSax("女");
    	emp.setEmployeePost("测试经理");
    	emp.setEmployeeDepartment("研发部");
    	int count =dao.insertEnterprise(emp);
    	if (count==1) {
			System.out.println("员工信息录入成功!");
		}else {
			System.out.println("员工信息录入失败!");
		}

    }

    public static void testUpdateEmp(){
    	employee emp=new employee();
    	emp.setEmployeeId(1);
    	emp.setEmployeeName("雷浩明");
    	emp.setEmployeeSax("男");
    	emp.setEmployeePost("CEO");
    	emp.setEmployeeDepartment("总裁办");
    	employeeDao dao=new employeeDaoimpal();
    	int count =dao.updateEnterprise(emp);
    	if (count==1) {
			System.out.println("员工信息修改成功!");
		}else {
			System.out.println("员工信息修改失败!");
		}

    }
    public static void testSelectEmp(){

    }
    public static void testDeleteEmp(){
    	employeeDao dao =new employeeDaoimpal();
		int count = dao.deleteEnterprise(11);
		if(count == 1){
			System.out.println("员工信息删除成功");
		}else {
			System.out.println("员工信息删除失败");
		}
    }

    public static void testGetCount(){
    	employeeDao dao =new employeeDaoimpal();
		System.out.println("共有"+dao.countAll()+"名员工");
	}

    public static void testGetEmpById(){
    	employeeDao dao =new employeeDaoimpal();
    	employee emp=dao.findEnterprise(1);
		System.out.println("职务是:"+emp.getEmployeePost()+"  所在部门:"+emp.getEmployeeDepartment());
	}

    public static void testGetAll(){
    	employeeDao dao =new employeeDaoimpal();
		List<employee> emps = dao.getAllEnterprise();
		System.out.println("西安涯创信息技术有限公司员工明细");
		System.out.println("---------------------------");
		System.out.println("员工编号\t员工姓名\t员工职位\t所在部门");
		for (employee emp : emps) {
			System.out.println(emp.getEmployeeId()+"\t"+emp.getEmployeeName()+"\t"+emp.getEmployeePost()+"\t"+emp.getEmployeeDepartment());
		}
	}

    public static void main(String[] args) {
    	 //testAddEmp();
    	 //testUpdateEmp();
    	 //testDeleteEmp();
    	 //testGetCount();
    	 //testGetEmpById();
    	   testGetAll();
	}

}

t_employee.sql

/*
SQLyog Ultimate v8.32
MySQL - 5.0.27-community : Database - test
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=‘‘*/;

/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `test`;

/*Table structure for table `t_employee` */

DROP TABLE IF EXISTS `t_employee`;

CREATE TABLE `t_employee` (
  `employeeid` int(10) NOT NULL COMMENT ‘员工id‘,
  `employeename` varchar(20) NOT NULL COMMENT ‘员工姓名‘,
  `employeesax` varchar(20) default NULL COMMENT ‘员工性别‘,
  `employeepost` varchar(30) NOT NULL COMMENT ‘员工职务‘,
  `employeedepartment` varchar(30) NOT NULL default ‘‘ COMMENT ‘员工所在部门‘,
  PRIMARY KEY  (`employeeid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

/*Data for the table `t_employee` */

insert  into `t_employee`(`employeeid`,`employeename`,`employeesax`,`employeepost`,`employeedepartment`) values (1,‘雷浩明‘,‘男‘,‘CEO‘,‘总裁办‘),(2,‘刘军‘,‘男‘,‘执行总裁‘,‘总裁办‘),(3,‘李海涛‘,‘男‘,‘总经理‘,‘总经办‘),(4,‘边肖‘,‘男‘,‘CTO‘,‘技术部‘),(5,‘柳青‘,‘女‘,‘经理‘,‘经营管理部‘),(6,‘高晓梅‘,‘女‘,‘财务‘,‘财务部‘),(7,‘曹舜水‘,‘男‘,‘研发经理‘,‘研发部‘),(8,‘董华‘,‘男‘,‘项目经理‘,‘研发部‘),(9,‘张军华‘,‘男‘,‘产品经理‘,‘产品部‘),(10,‘曾爽‘,‘女‘,‘测试经理‘,‘研发部‘);

/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40111 SET [email protected]_SQL_NOTES */;

项目代码结构截图:

项目需要的jar包下载地址:http://pan.baidu.com/s/1AWnPc。

时间: 2024-10-06 10:11:16

mybatis连接mysql数据库实现的jdbc功能的相关文章

JDBC 和 Mybatis连接mysql数据库的时候,设置字符集编码

jdbc连接MySQL数据库的时候,设置字符集编码!!! 可以如下配置,mysql可直接在url后面加上字符集设置: String url = "jdbc:mysql://localhost:3306/exceltest1?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"; Mybatis连接mysql数据库的时候,设置字符集编码!!! 可以如下配置,Mybatis的配

如何用IDEA创建springboot(maven)并且整合mybatis连接mysql数据库和遇到的问题

1.New->Project 2.点击next 3.在Group栏输入组织名,Artifact就是项目名.其它选择默认就好,直接Next 4.添加依赖 5.修改您希望放项目的位置,点击finish,等待idea下载springboot项目模板和相关的依赖 项目构建完成后的目录结构 6.如果需要用mybatis连接mysql数据库 a.添加连接数据库的依赖(在pom.xml中添加以下内容,maven将自动把相关依赖放到maven仓库中,然后放到项目中) <!--连接数据库--><de

mybatis连接mysql数据库插入中文乱码

对于mysql数据库的乱码问题,有两中情况: 1. mysql数据库编码问题(建库时设定). 2. 连接mysql数据库的url编码设置问题. 对于第一个问题,目前个人发现只能通过重新建库解决,建库的时候,选择UTF-8字符集.我试过修改现有数据库字符集为UFT -8,但是根本不起作用,插入的中文仍然乱码(中文显示成:???).重建库时选择字符集为UTF-8之后,中文正常显示了. 对于第二个问题,是这样 的情况:我建库时设置了数据库默认字符集为UTF-8,通过mysql workbench直接插

Mybatis连接mysql数据库出现乱码

对于mysql数据库的乱码问题,有两中情况: 1. mysql数据库编码问题(建库时设定). 2. 连接mysql数据库的url编码设置问题. 对于第一个问题,目前个人发现只能通过重新建库解决,建库的时候,选择UTF-8字符集.我试过修改现有数据库字符集为UFT -8,但是根本不起作用,插入的中文仍然乱码(中文显示成:???).重建库时选择字符集为UTF-8之后,中文正常显示了. 对于第二个问题,是这样的情况:我建库时设置了数据库默认字符集为UTF-8,通过mysql workbench直接插入

mybatis连接mysql数据库对数据增,删,改以及查询所有

mybatis对数据库的数据的操作 实体类 private int id;private String name;private int age; public int getId() { return id;}public void setId(int id) { this.id = id;} public String getName() { return name;}public void setName(String name) { this.name = name;} public i

Python学习笔记_02:使用Tkinter连接MySQL数据库实现登陆注册功能

1 环境搭建 1.1 Python安装 1.2 MySQL环境搭建 1.3安装MySQLdb  2 具体实现 2.1 登陆界面 2.2 注册界面 2.3 具体实现部分代码   1 环境搭建 1.1 Python安装 本文具体实现部分Python环境:Python2.7.14,64位版本 具体安装步骤见:Python 环境搭建 附:配置PythonIDE,推荐PyCharm(具体IDE界面见下图),下载点击运行即可使用 PyCharm 官方下载地址:http://www.jetbrains.com

Java 通过JDBC连接Mysql数据库的方法和实例——五部曲

一:把mysql-connector-java-5.1.20-bin.jar导入到本项目工程的目录下,步骤如下: (1)先新建一个Web Project项目,取项目名为test (2)右键点击工程下的JRE System Library --> Buid Path --> Configure Build Path --> Libraries --> Add Library --> User Library --> new --> 取名为MySQL --> 选

Ubuntu jsp平台使用JDBC来连接MySQL数据库

Ubuntu 7.04 搭建Ubuntu jsp平台开发环境MySQL+tomcat+apache+j2sdk1.6在所有安装开始前先在Terminal中输入 rpm -q -a查看是否安装过rpm 和 rpm包的所需软件如果没有安装rpm在Terminal中输入 sudo apt-get install rpm. AD:2014WOT全球软件技术峰会北京站 课程视频发布 你们知道什么是Ubuntu jsp平台么这个非常高深的运用技术将由我来非常讲解,Ubuntu jsp平台NB在哪呢,下面我来

Java基础102 完整的JDBC连接MySQL数据库和Oracle数据库的方法

本文知识点(目录): 1.jdbc连接MySQL数据库    2.jdbc连接Oracle数据库    3.附录[本文jdbc连接MySQL或Oracle数据库的全部代码(合起来,做对比)] 1.JDBC连接MySQL数据库 1.1.我用到的jar包 1.2.实例演示 MySQL建表语句 1 -- MySQL建表语句 2 create table user( 3 id number(5) primary key auto_increment, 4 account varchar(20) not