免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4346 | 回复: 0
打印 上一主题 下一主题

mybatis连接mysql数据库实现的jdbc功能 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-06-17 09:45 |只看该作者 |倒序浏览
最近公司项目要使用myBatis,自己以前没有接触过,就在网上找到了一些资料研究了些。初步做出了基于myBatis连接mysql数据库的jdbc实现的功能。项目需要的jar包下载地址:http://pan.baidu.com/s/1AWnPc
employee.java
  1. package com.org.position.model;

  2. public class employee {
  3.     private int     employeeId;// 员工id
  4.     private String  employeeName; //员工姓名
  5.     private String  employeeSax; //员工性别
  6.     private String  employeePost; //员工职务
  7.     private String  employeeDepartment; //员工所在部门
  8.      
  9.     public int getEmployeeId() {
  10.         return employeeId;
  11.     }
  12.     public void setEmployeeId(int employeeId) {
  13.         this.employeeId = employeeId;
  14.     }
  15.     public String getEmployeeName() {
  16.         return employeeName;
  17.     }
  18.     public void setEmployeeName(String employeeName) {
  19.         this.employeeName = employeeName;
  20.     }
  21.     public String getEmployeeSax() {
  22.         return employeeSax;
  23.     }
  24.     public void setEmployeeSax(String employeeSax) {
  25.         this.employeeSax = employeeSax;
  26.     }
  27.     public String getEmployeePost() {
  28.         return employeePost;
  29.     }
  30.     public void setEmployeePost(String employeePost) {
  31.         this.employeePost = employeePost;
  32.     }
  33.     public String getEmployeeDepartment() {
  34.         return employeeDepartment;
  35.     }
  36.     public void setEmployeeDepartment(String employeeDepartment) {
  37.         this.employeeDepartment = employeeDepartment;
  38.     }
  39.      
  40. }
复制代码
employeeDao.java
  1. package com.org.position.dao;


  2. import java.util.List;

  3. import com.org.position.model.employee;

  4. public interface employeeDao {
  5.    public int countAll();
  6.    public employee findEnterprise(int employeeId);
  7.    public int insertEnterprise(employee emp);
  8.    public int deleteEnterprise(int employeeId);
  9.    public List<employee> getAllEnterprise();
  10.    public int updateEnterprise(employee emp );
  11.    public List<employee> findEnterpriseByExampleIf(employee emp);
  12.    
  13. }
复制代码
employeeDaoimpal.java
  1. package com.org.position.dao.impal;

  2. import java.io.IOException;
  3. import java.io.Reader;
  4. import java.util.List;

  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;

  9. import com.org.position.dao.employeeDao;
  10. import com.org.position.model.employee;

  11. public class employeeDaoimpal implements employeeDao {

  12.     @Override
  13.     public int countAll() {
  14.         String resource="mybaits-config.xml";
  15.         Reader reader=null;
  16.         SqlSessionFactory  ssf=null;
  17.         SqlSession session=null;
  18.         int iCount=0;
  19.         try {
  20.             reader= Resources.getResourceAsReader(resource);
  21.             SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
  22.             ssf=builder.build(reader);
  23.             session=ssf.openSession();
  24.             iCount=session.selectOne("com.org.position.dao.employeeDao.countAll");
  25.         } catch (IOException e) {
  26.             e.printStackTrace();
  27.         }
  28.         finally{
  29.             session.close();
  30.         }
  31.         return iCount;
  32.     }

  33.     @Override
  34.     public employee findEnterprise(int employeeId) {
  35.         String resource="mybaits-config.xml";
  36.         Reader reader=null;
  37.         SqlSessionFactory  ssf=null;
  38.         SqlSession session=null;
  39.         employee  emp=null;
  40.         try {
  41.             reader = Resources.getResourceAsReader(resource);
  42.             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  43.             ssf = builder.build(reader);
  44.             session=ssf.openSession();
  45.             employeeDao empdao=session.getMapper(employeeDao.class);
  46.             emp=empdao.findEnterprise(employeeId);
  47.         } catch (IOException e) {
  48.             // TODO Auto-generated catch block
  49.             e.printStackTrace();
  50.         }finally{
  51.             session.close();
  52.         }
  53.          
  54.         return emp;
  55.     }

  56.     @Override
  57.     public int insertEnterprise(employee emp) {
  58.         String resource="mybaits-config.xml";
  59.         Reader reader=null;
  60.         SqlSessionFactory  ssf=null;
  61.         SqlSession session=null;
  62.         int count=0;
  63.         try {
  64.             reader = Resources.getResourceAsReader(resource);
  65.             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  66.             ssf = builder.build(reader);
  67.             session=ssf.openSession();
  68.             count=session.insert("com.org.position.dao.employeeDao.insertEnterprise",emp);
  69.             session.commit();
  70.         } catch (IOException e) {
  71.             // TODO Auto-generated catch block
  72.             e.printStackTrace();
  73.         }
  74.         finally{
  75.             session.close();
  76.         }
  77.         return count;
  78.     }

  79.     @Override
  80.     public int deleteEnterprise(int employeeId) {
  81.         String resource="mybaits-config.xml";
  82.         Reader reader = null;
  83.         SqlSessionFactory ssf=null;
  84.         SqlSession session=null;
  85.         int iCount = 0;
  86.         try {
  87.             reader = Resources.getResourceAsReader(resource);
  88.             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  89.             ssf = builder.build(reader);
  90.             session=ssf.openSession();
  91.             iCount=session.delete("com.org.position.dao.employeeDao.deleteEnterprise", employeeId);
  92.             session.commit();
  93.         } catch (IOException e) {
  94.             // TODO Auto-generated catch block
  95.             e.printStackTrace();
  96.         }finally{
  97.             session.close();
  98.         }
  99.          
  100.         return iCount;
  101.     }

  102.     @Override
  103.     public List<employee> getAllEnterprise() {
  104.         String resource="mybaits-config.xml";
  105.         Reader reader = null;
  106.         SqlSessionFactory ssf=null;
  107.         SqlSession session=null;
  108.         List<employee> emps = null;
  109.         try {
  110.             reader = Resources.getResourceAsReader(resource);
  111.             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  112.             ssf = builder.build(reader);
  113.             session=ssf.openSession();
  114.             emps=session.selectList("com.org.position.dao.employeeDao.getAllEnterprise");
  115.         } catch (IOException e) {
  116.             // TODO Auto-generated catch block
  117.             e.printStackTrace();
  118.         }
  119.         finally{
  120.             session.close();
  121.         }
  122.         return emps;
  123.     }

  124.     @Override
  125.     public int updateEnterprise(employee emp) {
  126.         String resource="mybaits-config.xml";
  127.         Reader reader = null;
  128.         SqlSessionFactory ssf=null;
  129.         SqlSession session=null;
  130.         int iCount = 0;
  131.             try {
  132.                 reader = Resources.getResourceAsReader(resource);
  133.                 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  134.                  
  135.                 ssf = builder.build(reader);
  136.                 session=ssf.openSession();
  137.                 iCount=session.delete("com.org.position.dao.employeeDao.updateEnterprise",emp);
  138.                 session.commit();
  139.             } catch (IOException e) {
  140.                 // TODO Auto-generated catch block
  141.                 e.printStackTrace();
  142.             }finally{
  143.                 session.close();
  144.             }
  145.          
  146.          
  147.         return iCount;
  148.     }

  149.     @Override
  150.     public List<employee> findEnterpriseByExampleIf(employee emp) {
  151.         String resource="mybatis-config.xml";
  152.         Reader reader = null;
  153.         SqlSessionFactory ssf=null;
  154.         SqlSession session=null;
  155.         List<employee> emps = null;
  156.         try {
  157.             reader = Resources.getResourceAsReader(resource);
  158.             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  159.             ssf = builder.build(reader);
  160.             session=ssf.openSession();
  161.             emps=session.selectList("com.org.position.dao.employeeDao.findEnterpriseByExampleIf",emp);
  162.         } catch (IOException e) {
  163.             // TODO Auto-generated catch block
  164.             e.printStackTrace();
  165.         }finally{
  166.             session.close();
  167.         }
  168.          
  169.         return emps;
  170.     }

  171. }
复制代码
employeeDaoMapper.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>   

  2. <!DOCTYPE mapper   
  3. PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
  4. "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
  5. <mapper  namespace="com.org.position.dao.employeeDao">
  6.   <resultMap type="com.org.position.model.employee" id="empResultMap">
  7.     <id property="employeeId" column="employeeId"/>
  8.     <result property="employeeName" column="employeeName" />
  9.     <result property="employeeSax" column="employeeSax"/>
  10.     <result property="employeePost" column="employeePost"/>
  11.      <result property="employeeDepartment" column="employeeDepartment"/>
  12.   </resultMap>
  13.    <select id="findEnterpriseByExampleIf" parameterType="com.org.position.model.employee"  resultMap="empResultMap">
  14.       select * from employee where 1=1
  15.      <if test="employeed !=null">
  16.          and employeeId=#{employeeId}
  17.      </if>
  18.        <if test="employeename!=null">
  19.          and employeeName=#{employeeName}
  20.        </if>
  21.         <if test="employeesax! =null">
  22.          and employeeSax=#{employeeSax}
  23.         </if>
  24.         <if test="employeepost!=null">
  25.          and employeePost=#{employeePost}
  26.         </if>
  27.         <if test="employeedepartment! =null">
  28.          and  employeeDepartment=#{employeeDepartment}
  29.         </if>
  30.    </select>
  31.   
  32.    <select id="countAll"  resultType="int">
  33.        select count(*) from t_employee
  34.    </select>
  35.   <!--   根据id查询对应的数据信息 -->
  36.    <select id="findEnterprise" parameterType="int" resultType="com.org.position.model.employee">
  37.      select * from t_employee where employeeId=#{employeeId}
  38.    </select>
  39.     <!--    查询所有 数据 -->
  40.    <select id="getAllEnterprise" resultType="com.org.position.model.employee">
  41.       select * from t_employee
  42.    </select>
  43.         <!-- 添加数据信息 -->
  44.    <insert id="insertEnterprise" parameterType="com.org.position.model.employee">
  45.         insert into  t_employee(employeeId,employeeName,employeeSax,employeePost,employeeDepartment)
  46.         values (#{employeeId},#{employeeName},#{employeeSax},#{employeePost},#{employeeDepartment})
  47.    </insert>
  48.         <!-- 更新数据信息 -->
  49.    <update id="updateEnterprise" parameterType="com.org.position.model.employee">
  50.      update t_employee set employeeName=#{employeeName},employeeSax=#{employeeSax},employeePost=#{employeePost},employeeDepartment=#{employeeDepartment}
  51.      where employeeId=#{employeeId}
  52.    </update>
  53.     <!-- 删除数据信息 -->
  54.    <delete id="deleteEnterprise" parameterType="com.org.position.model.employee">
  55.     delete from t_employee where employeeId=#{employeeId}
  56.    
  57.    </delete>
  58. </mapper>
复制代码
mybaits-config.xm
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5.    <environments default="development">
  6.      <environment id="development">
  7.      <transactionManager type="JDBC"></transactionManager>
  8.      <dataSource type="POOLED">
  9.      <property name="driver" value="com.mysql.jdbc.Driver"/>
  10.      <property name="url" value="jdbc:mysql://localhost:3306/test"/>
  11.      <property name="username" value="root"/>
  12.      <property name="password" value="mysql"/>
  13.      </dataSource>
  14.      </environment>
  15.    </environments>
  16.   <mappers>
  17.     <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  18.   </mappers>
  19. </configuration>
复制代码
mybaits-config.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5.    <environments default="development">
  6.      <environment id="development">
  7.      <transactionManager type="JDBC"></transactionManager>
  8.      <dataSource type="POOLED">
  9.      <property name="driver" value="com.mysql.jdbc.Driver"/>
  10.      <property name="url" value="jdbc:mysql://localhost:3306/test"/>
  11.      <property name="username" value="root"/>
  12.      <property name="password" value="mysql"/>
  13.      </dataSource>
  14.      </environment>
  15.    </environments>
  16.   <mappers>
  17.     <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  18.   </mappers>
  19. </configuration>
复制代码
employeeTest.java
  1. package com.org.position.test;

  2. import java.util.List;

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

  6. public class employeeTest {
  7.      
  8.     public static void testAddEmp(){
  9.         employee emp=new employee();
  10.         employeeDao dao=new employeeDaoimpal();
  11.         emp.setEmployeeId(11);
  12.         emp.setEmployeeName("爽");
  13.         emp.setEmployeeSax("女");
  14.         emp.setEmployeePost("测试经理");
  15.         emp.setEmployeeDepartment("研发部");
  16.         int count =dao.insertEnterprise(emp);
  17.         if (count==1) {
  18.             System.out.println("员工信息录入成功!");
  19.         }else {
  20.             System.out.println("员工信息录入失败!");
  21.         }
  22.          
  23.          
  24.     }
  25.      
  26.     public static void testUpdateEmp(){
  27.         employee emp=new employee();
  28.         emp.setEmployeeId(1);
  29.         emp.setEmployeeName("雷浩明");
  30.         emp.setEmployeeSax("男");
  31.         emp.setEmployeePost("CEO");
  32.         emp.setEmployeeDepartment("总裁办");
  33.         employeeDao dao=new employeeDaoimpal();
  34.         int count =dao.updateEnterprise(emp);
  35.         if (count==1) {
  36.             System.out.println("员工信息修改成功!");
  37.         }else {
  38.             System.out.println("员工信息修改失败!");
  39.         }
  40.          
  41.     }
  42.     public static void testSelectEmp(){
  43.          
  44.     }
  45.     public static void testDeleteEmp(){
  46.         employeeDao dao =new employeeDaoimpal();
  47.         int count = dao.deleteEnterprise(11);
  48.         if(count == 1){
  49.             System.out.println("员工信息删除成功");
  50.         }else {
  51.             System.out.println("员工信息删除失败");
  52.         }
  53.     }
  54.      
  55.     public static void testGetCount(){
  56.         employeeDao dao =new employeeDaoimpal();
  57.         System.out.println("共有"+dao.countAll()+"名员工");
  58.     }
  59.      
  60.     public static void testGetEmpById(){
  61.         employeeDao dao =new employeeDaoimpal();
  62.         employee emp=dao.findEnterprise(1);
  63.         System.out.println("职务是:"+emp.getEmployeePost()+"  所在部门:"+emp.getEmployeeDepartment());
  64.     }
  65.      
  66.     public static void testGetAll(){
  67.         employeeDao dao =new employeeDaoimpal();
  68.         List<employee> emps = dao.getAllEnterprise();
  69.         System.out.println("西安涯创信息技术有限公司员工明细");
  70.         System.out.println("---------------------------");
  71.         System.out.println("员工编号\t员工姓名\t员工职位\t所在部门");
  72.         for (employee emp : emps) {
  73.             System.out.println(emp.getEmployeeId()+"\t"+emp.getEmployeeName()+"\t"+emp.getEmployeePost()+"\t"+emp.getEmployeeDepartment());
  74.         }
  75.     }
  76.      
  77.     public static void main(String[] args) {
  78.          //testAddEmp();
  79.          //testUpdateEmp();
  80.          //testDeleteEmp();
  81.          //testGetCount();
  82.          //testGetEmpById();
  83.            testGetAll();
  84.     }
  85.      
  86. }
复制代码
t_employee.sql
  1. /*
  2. SQLyog Ultimate v8.32
  3. MySQL - 5.0.27-community : Database - test
  4. *********************************************************************
  5. */


  6. /*!40101 SET NAMES utf8 */;

  7. /*!40101 SET SQL_MODE=''*/;

  8. /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
  9. /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
  10. /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
  11. /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
  12. CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;

  13. USE `test`;

  14. /*Table structure for table `t_employee` */

  15. DROP TABLE IF EXISTS `t_employee`;

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

  24. /*Data for the table `t_employee` */

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

  26. /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
  27. /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
  28. /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
  29. /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP