问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501

使用mybatis与直接用jdbc相比,有哪些优势?

发布网友 发布时间:2022-04-07 20:09

我来回答

3个回答

懂视网 时间:2022-04-08 00:31

最近公司项目要使用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("员工编号	员工姓名	员工职位	所在部门");
		for (employee emp : emps) {
			System.out.println(emp.getEmployeeId()+"	"+emp.getEmployeeName()+"	"+emp.getEmployeePost()+"	"+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 @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @OLD_SQL_NOTES=@@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 SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

项目代码结构截图:

技术分享

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

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

标签:

热心网友 时间:2022-04-07 21:39

2、mybatis已有的连接池管理,缓存管理等所带来的代码性能优势和可靠性(作为一个工业级的开源框架,其代码是久经考验的);
3、一致的编码风格大大减少了代码的沟通交流成本;

热心网友 时间:2022-04-07 22:57

a. MyBatis使用SqlSessionFactoryBuilder来完成JDBC需要代码完成的数据库获取和连接,减少了代码的重复
b. MyBatis是将sql语句写入xml中,易于修改和维护;JDBC将sql语句写到代码里属于硬编码,非常不易维护。
c. JDBC的resultSet需要用户自己去读取并生成对应的pojo,MyBatis的mapper会自动将执行后的结果映射到对应的java对象中。
d. 使用MyBatis的编码风格统一优雅、性能高,灵活性好
声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com
为什么来大姨妈胸会胀 少儿学什么舞蹈 青年学什么舞蹈好 成年人学什么舞蹈 福州企业最低工资标准 2013年厦门的底薪是多少 生产要素的需求有哪些性质 生产要素的需求有何特点? 什么是生产要素需求 微观经济学要素需求什么是条件要素需求?它和要素需求有什么不同?_百度... 什么叫环氧地坪? 您好,请问环氧地坪的防火等级? 在国标中有没有关于环氧地坪漆的标准和防火检测报告? 地下车库地坪漆防火等级? 水泥自流平国标 环氧树脂自流平地面的防火等级是? 什么样的地坪可以达到防火A级 家里的笔记本电脑是用宽带连接快还是wifi连接快呢? 笔记本怎么判断是宽带连接还是wifi, 阔腿裤早就失宠了,万能裙时髦减龄还百搭,你觉得呢? 笔记本电脑如何连接无线笔记本电脑如何连接无线WIFI?为什么,只能连接宽带网络 三伏天又火了哪种上衫,搭半身裙、阔腿裤都好看? 家里拉了宽带并安有路由器请问笔记本首选宽带连接还是wiFi,那个速度快些? 衬衫裙+阔腿裤绝配!女生如何穿才显得格外新潮? 阔腿裤已经是过去式,今年流行各种各样的裙子,怎样搭配才最好看? 小学中队长工作总结怎么写 急,请今天发过来 四年级中队长的工作总结报告怎么写?急急急!(50—150字) 小学中队长自我评价怎么写 初二竞选中队长,跪求求一份竞选稿,谢谢了,好的追100分! 马克水印相机的水印可以调整大小吗? 自流平强度等级分类 环氧地坪的防火等级是怎么划分的 水泥基自流平楼面是否怕水 请问: 水泥自流平是有哪些要求的,而且还是需要注意些什么呢? catia中创建局部剖视图怎么进行深度定义 自流平水泥的性能是什么? 楼房屋地面隔音隔热水泥发泡自流平如何验收 请问环氧地坪的防火等级? catia里怎样把模型剖开看里面结构 家装中如何作水泥自流平,对基层有什么要求? catia怎么在视图上做局部剖视,而不是生成独立的剖视图? 水泥自流平在施工时应注意哪些事项呢? catia如何局部剖视图 catia同时存在两个A-A剖视图 机械制图,catia工程制图里做的剖视图怎样才能移动到图纸页面的任意位置? catia如何画半剖视图 catia颜色更改及剖视图 catia剖视图只显示剖面,不显示其余轮廓线该如何设置? 龙的图片(用于初一学生画画) catia工程制图中剖视图!