程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SyBase數據庫 >> SyBase教程 >> Mybatis接口編程方式實現增刪改查

Mybatis接口編程方式實現增刪改查

編輯:SyBase教程

Mybatis接口編程方式實現增刪改查


前面一章Mybatis入門概述及第一個Mybatis實例實現增刪改查 ,已經搭建好了eclipse,mybatis,mysql的環境,並且實現了一個簡單的查詢。請注意,這種方式是用SqlSession實例來直接執行已映射的SQL語句:

session.selectOne("com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);

其實還有更簡單的方法,而且是更好的方法,使用合理描述參數和SQL語句返回值的接口(比如EmployeerMapper.java),這樣現在就可以至此那個更簡單,更安全的代碼,沒有容易發生的字符串文字和轉換的錯誤.下面是詳細過程:

本文要改成以接口類來實現增刪改查

整個工程目錄 :

\

本文示例工程免費下載

1、首先還是mybatis的配置文件mybatis-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>  
    <!-- 元素允許在主配置文件之外提供一個properties格式對應文件,從而使得主配置文件更加通用。這樣對部署非常有用  -->  
     <properties resource="mysql.properties" />   
    <!-- 設置別名,一定要放在properties下面  -->  
    <typeAliases>  
        <typeAlias alias="Employeer" type="com.mucfc.model.Employeer"  />  
    </typeAliases>  
    <!-- 配置數據源相關的信息  -->  
    <environments default="development">  
        <environment id="development">  
            <transactionManager type="JDBC" />  
            <dataSource type="POOLED">  
        <!--     <property name="driver" value="com.mysql.jdbc.Driver"/>  
             <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/>   
            <property name="username" value="root"/>   
            <property name="password" value="christmas258@"/>  -->  
            <property name="driver" value="${driver}" />  
                <property name="url" value="${url}" />  
                <property name="username" value="${username}" />  
                <property name="password" value="${password}" />   
            </dataSource>  
        </environment>  
    </environments>  
    <!-- 列出映射文件 -->  
    <mappers>  
        <mapper resource="com/mucfc/model/Employeer.xml" />  
    </mappers>  
</configuration>  

其中配置文件mysql.properties

 

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?charset=utf8
username=root
password=christmas258@


 

2、數據表對應的類Employeer.JAVA

 

package com.mucfc.model;

import java.io.Serializable;

/**
 * 雇員信息類
 *@author linbingwen
 *@time 2015.5.11
 */
public class Employeer {
	private Integer employeer_id;
	private String employeer_name;
	private Integer employeer_age ;
	private String employeer_department;
	private String employeer_worktype;
	
	public Employeer() {
		super();
	}
	public Integer getEmployeer_id() {
		return employeer_id;
	}
	public void setEmployeer_id(Integer employeer_id) {
		this.employeer_id = employeer_id;
	}
	public String getEmployeer_name() {
		return employeer_name;
	}
	public void setEmployeer_name(String employeer_name) {
		this.employeer_name = employeer_name;
	}
	public Integer getEmployeer_age() {
		return employeer_age;
	}
	public void setEmployeer_age(Integer employeer_age) {
		this.employeer_age = employeer_age;
	}
	public String getEmployeer_department() {
		return employeer_department;
	}
	public void setEmployeer_department(String employeer_department) {
		this.employeer_department = employeer_department;
	}
	public String getEmployeer_worktype() {
		return employeer_worktype;
	}
	public void setEmployeer_worktype(String employeer_worktype) {
		this.employeer_worktype = employeer_worktype;
	}
	@Override
	public String toString() {
		return "Employeer [employeer_id=" + employeer_id + ", employeer_name="
				+ employeer_name + ", employeer_age=" + employeer_age
				+ ", employeer_department=" + employeer_department
				+ ", employeer_worktype=" + employeer_worktype + "]";
	}
	


}
然後是SQL語句的配置Employeer.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.mucfc.mapper.EmployeerMapper">  
   
     <!-- 查找 -->  
     <select id="findEmployeerByID" parameterType="int" resultType="Employeer">  
     select* from `t_employeer` where employeer_id =#{employeer_id}  
     </select>  
       
      <!-- 插入 -->    
      <!-- useGeneratedKeys設置為"true"表明要MyBatis獲取由數據庫自動生成的主鍵;keyProperty="id"指定把獲取到的主鍵值注入到Employeer的id屬性 -->   
    <insert id="addEmployeer" parameterType="Employeer"  
    useGeneratedKeys="true" keyProperty="employeer_id">    
        insert into `t_employeer`(employeer_name,employeer_age,employeer_department,employeer_worktype)   
        values(#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype})    
    </insert>    
      
     <!-- 刪除  -->  
    <delete id="deleteEmployeer" parameterType="int">    
        delete from `t_employeer` where employeer_id = #{employeer_id}    
    </delete>    
      
    <!-- 修改 -->    
    <update id="updateEmployeer" parameterType="Employeer">    
        update t_employeer set employeer_name = #{employeer_name},employeer_age= #{employeer_age},employeer_department = #{employeer_department}  
        ,employeer_worktype=#{employeer_worktype}  where employeer_id = #{employeer_id}    
    </update>    
      
 </mapper>  


注意com.mucfc.mapper.EmployeerMapper這個類是存在的,它是一個接口類,上一講我們是使用com.mucfc.model.EmployeerMapper,而上一講的這個類是不存在的

 

4、SQL語句映射類EmployeerMapper.java

 

package com.mucfc.mapper;

import com.mucfc.model.Employeer;

/**
 * SQL語句映射類
 * @author linbingwen
 * @time 2015.5.11
 */
public interface EmployeerMapper {
	/**
	 * 注意要和Employeer.xml的方法名對應
	 */
	public Employeer findEmployeerByID(int id);

	/**
	 * 注意要和Employeer.xml的方法名對應
	 */
	public void addEmployeer(Employeer employeer);

	/**
	 * 注意要和Employeer.xml的方法名對應
	 */
	public void deleteEmployeer(int id);

	/**
	 * 注意要和Employeer.xml的方法名對應
	 */
	public void updateEmployeer(Employeer employeer);

}
5、測試:

 

 

(1)增加命令

上一講Mybatis入門概述及第一個Mybatis實例實現增刪改查 中的方式:

 

	/**
	 * 增加
	 */
	public static void addEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			 //返回值是記錄條數  
            int resultCount = session.insert("com.mucfc.model.EmployeerMapper.addEmployeer", employeer );  
            System.out.printf("當前插入的employeer_id :%d    當前插入數據庫中條數:%d " , employeer.getEmployeer_id() ,resultCount);  //獲取插入對象的id  
            System.out.println("");
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}


改成以接口編程的方式:

 

 

	/**
	 * 增加
	 */
	public static void addEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.addEmployeer(employeer);
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}

(2)刪除命令

 

上一講【Mybatis】Mybatis入門概述及第一個Mybatis實例實現增刪改查 中的方式:

 

	/**
	 * 刪除
	 * 
	 */
	public static void deleteEmployeer(int id){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			 //返回值是記錄條數  
			 int resultCount=session.delete("com.mucfc.model.EmployeerMapper.deleteEmployeer",id); 
			  System.out.println("當前刪除數據庫中條數: "+resultCount);  //獲取插入對象的id  
            session.commit() ;  		
		} finally {
			session.close();
		}
	}


 

改成以接口編程的方式:

 

	/**
	 * 刪除
	 * 
	 */
	public static void deleteEmployeer(int id){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.deleteEmployeer(id);
            session.commit() ;  		
		} finally {
			session.close();
		}
	}


 

(3)查找命令

上一講【Mybatis】Mybatis入門概述及第一個Mybatis實例實現增刪改查 中的方式:

 

	/**
	 * 查找
	 */
	public static void findEmployeerById(int id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			Employeer employeer = (Employeer) session.selectOne(
					"com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);
			if (employeer == null)
				System.out.println("null");
			else
				System.out.println(employeer);
		} finally {
			session.close();
		}
	}


 

改成以接口編程的方式:

 

/**
	 * 查找
	 */
	public static void findEmployeerById(int id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			Employeer employeer=employeerMapper.findEmployeerByID(id);
			if (employeer == null)
				System.out.println("null");
			else
				System.out.println(employeer);
		} finally {
			session.close();
		}
	}

 

 

(4)修改命令

上一講【Mybatis】Mybatis入門概述及第一個Mybatis實例實現增刪改查 中的方式:

 

	/**
	 * 更改
	 */
	public static void updateEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession(); 
            session.update("com.mucfc.model.EmployeerMapper.updateEmployeer",employeer);    
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}


 

改成以接口編程的方式:

 

	/**
	 * 更改
	 */
	public static void updateEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession(); 
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.updateEmployeer(employeer);
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}

這是一個完整的測試:

 

 

package com.mucfc.test;

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

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.mucfc.mapper.EmployeerMapper;
import com.mucfc.model.Employeer;

public class MybatisTest {
	private static SqlSessionFactory sqlSessionFactory;
	private static Reader reader;
	static {
		try {
			reader = Resources.getResourceAsReader("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查找
	 */
	public static void findEmployeerById(int id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			Employeer employeer=employeerMapper.findEmployeerByID(id);
			if (employeer == null)
				System.out.println("null");
			else
				System.out.println(employeer);
		} finally {
			session.close();
		}
	}
	/**
	 * 增加
	 */
	public static void addEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.addEmployeer(employeer);
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}
	/**
	 * 刪除
	 * 
	 */
	public static void deleteEmployeer(int id){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.deleteEmployeer(id);
            session.commit() ;  		
		} finally {
			session.close();
		}
	}
	/**
	 * 更改
	 */
	public static void updateEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession(); 
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.updateEmployeer(employeer);
            session.commit() ;  		
		} finally {
			session.close();
		}
		
	}

	public static void main(String[] args) {							
		Employeer employeer1=new Employeer();
		employeer1.setEmployeer_name("李四");
		employeer1.setEmployeer_age(23);
		employeer1.setEmployeer_department("產品一部");
		employeer1.setEmployeer_worktype("開發工程師");
		
		Employeer employeer2=new Employeer();
		employeer2.setEmployeer_name("張三");
		employeer2.setEmployeer_age(30);
		employeer2.setEmployeer_department("產品二部");
		employeer2.setEmployeer_worktype("測試工程師");
		
		Employeer employeer3=new Employeer();
		employeer3.setEmployeer_name("小王");
		employeer3.setEmployeer_age(22);
		employeer3.setEmployeer_department("產品三部");
		employeer3.setEmployeer_worktype("數據分析師");
		
		
		Employeer employeer4=new Employeer();
		employeer4.setEmployeer_name("明明");
		employeer4.setEmployeer_age(22);
		employeer4.setEmployeer_department("財會部");
		employeer4.setEmployeer_worktype("財務人員");
	
		//插入
     	addEmployeer(employeer1);
     	addEmployeer(employeer2);
     	addEmployeer(employeer3);
     	addEmployeer(employeer4);
     	findEmployeerById(26);
     	deleteEmployeer(27);
		
		//更改
		employeer2.setEmployeer_id(28);
		employeer2.setEmployeer_age(21);
		employeer2.setEmployeer_department("產品四部");
		updateEmployeer(employeer2);

	}

}

測試結果:

 

插入了4條數據,ID為25~28

然後27號被刪除

29號被修改

\

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved