MyBatis的應用

a)首先先導入固定的jar包java

b)添加mybatis配置文件mybatis-config.xmlweb

一、添加mybatis配置文件mybatis-config.xmlspring

<?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>
     <settings>
         <setting name="cacheEnabled" value="true" />  <!-- 緩存 -->
        <setting name="useGeneratedKeys" value="true" /> <!--  自動獲取主鍵 -->
        <setting name="defaultExecutorType" value="REUSE" /> 
     </settings>
    <!-- 配置別名 -->
     <typeAliases>
         <typeAlias alias="User" type="com.sdtg.system.bean.User"/>
         <typeAlias alias="Dept" type="com.sdtg.system.bean.Dept"/>
         <typeAlias alias="UserDept" type="com.sdtg.system.bean.UserDept"/>
         <typeAlias alias="Module" type="com.sdtg.system.bean.Module"/>
         <typeAlias alias="Privilege" type="com.sdtg.system.bean.Privilege"/>
         <typeAlias alias="Role" type="com.sdtg.system.bean.Role"/>
         <typeAlias alias="RolePrivilege" type="com.sdtg.system.bean.RolePrivilege"/>
         <typeAlias alias="OperateLog" type="com.sdtg.system.bean.OperateLog"/>
         <typeAlias alias="UserPrivilege" type="com.sdtg.system.bean.UserPrivilege"/>
         <typeAlias alias="WorkPlan" type="com.sdtg.plan.bean.WorkPlan"/>
         <typeAlias alias="Notepad" type="com.sdtg.office.bean.Notepad"/>
         <typeAlias alias="Onduty" type="com.sdtg.office.bean.Onduty"/>
         <typeAlias alias="Company" type="com.sdtg.contacts.bean.Company"/>
         <typeAlias alias="News" type="com.sdtg.contacts.bean.News"/>
         <typeAlias alias="Customer" type="com.sdtg.contacts.bean.Customer"/>
         <typeAlias alias="Files" type="com.sdtg.file.bean.Files"/>
     </typeAliases>
     <!-- 配置mappers -->
     <!-- mappers元素是包含全部mapper(映射器)的列表,這些mapper的XML文件包含SQL代碼和映射定義信息。 -->
     <mappers>
         <mapper resource="com/sdtg/system/dao/User.xml"/>
        <mapper resource="com/sdtg/system/dao/Dept.xml"/>
        <mapper resource="com/sdtg/system/dao/Module.xml"/>
        <mapper resource="com/sdtg/system/dao/Privilege.xml"/>
        <mapper resource="com/sdtg/system/dao/Role.xml"/>
        <mapper resource="com/sdtg/system/dao/OperateLog.xml"/>
        <mapper resource="com/sdtg/plan/dao/WorkPlan.xml"/>
        <mapper resource="com/sdtg/office/dao/Notepad.xml"/>
        <mapper resource="com/sdtg/office/dao/Onduty.xml"/>
        <mapper resource="com/sdtg/contacts/dao/Company.xml"/>
        <mapper resource="com/sdtg/contacts/dao/News.xml"/>
        <mapper resource="com/sdtg/contacts/dao/Customer.xml"/>
        <mapper resource="com/sdtg/file/dao/Files.xml"/>
     </mappers>
 </configuration>

二、建立對應的實體對象sql

對應的java代碼數據庫

 1 package com.sdtg.contacts.bean;
 2 
 3 import java.io.Serializable;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.Id;
 9 import javax.persistence.Table;
10 
11 import org.hibernate.annotations.GenericGenerator;
12 
13 @Entity
14 @Table(name = "company") // 映射數據庫中表的表名
15 public class Company implements Serializable {
16 
17     private static final long serialVersionUID = -7746115557660768065L;
18 
19     @Id
20     @Column(name = "c_id") //映射company表的c_id列
21     @GenericGenerator(name = "idGenerator", strategy = "identity")//name屬性指定生成器名稱,strategy屬性指定具體生成器的類名。
22     @GeneratedValue(generator = "idGenerator")
23     private Integer id;//主鍵
24     
25     @Column(name = "c_name")
26     private String name;//名稱
27     
28     @Column(name = "c_address")
29     private String address;//地址
30     
31     @Column(name = "c_tel")
32     private String tel;//電話
33 
34     public Company() {
35         super();    
36     }
37 
38     public Integer getId() {
39         return id;
40     }
41 
42     public void setId(Integer id) {
43         this.id = id;
44     }
45 
46     public String getName() {
47         return name;
48     }
49 
50     public void setName(String name) {
51         this.name = name;
52     }
53 
54     public String getAddress() {
55         return address;
56     }
57 
58     public void setAddress(String address) {
59         this.address = address;
60     }
61 
62     public String getTel() {
63         return tel;
64     }
65 
66     public void setTel(String tel) {
67         this.tel = tel;
68     }
69     
70     
71 }
View Code

三、建立接口和對應的定義操做company表的sql映射文件Company.xml(以company爲例)spring-mvc

接口提供簡單的增刪改查數據的信息緩存

package com.sdtg.contacts.dao;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.sdtg.contacts.bean.Company;

@Repository //標註一個DAO類組件類
public interface CompanyDao {
    
    /**
     * 查詢
     * @param map
     * @return
     */
    public abstract List<Company> find(Map<String, Object> map);
    
    /**
     * 分頁查詢
     * @param map
     * @return
     */
    public abstract List<Company> findPage(Map<String, Object> map);
    
    /**
     * 查詢條數
     * @param map
     * @return
     */
    public abstract Integer findCount(Map<String, Object> map);
    
    /**
     * id查詢
     * @param id
     * @return
     */
    public abstract Company findById(Integer id);
    
    /**
     * 添加
     * @param company
     */
    public abstract void add(Company company);
    
    /**
     * 刪除
     * @param id
     */
    public abstract void delete(Integer id);
    
    /**
     * 修改
     * @param company
     */
    public abstract void update(Company company);

}

 

 

Company.xml文件運用sql語句進行對數據信息的增刪改查session

<?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.sdtg.contacts.dao.CompanyDao">
    
    <!-- 字段 -->
    <sql id="field">
        c.c_id as 'id',
        c.c_name as 'name',
        c.c_address as 'address',
        c.c_tel as 'tel'
    </sql>
    
    <!-- 條件 -->
    <sql id="sql">
        <if test="name != null and name != ''">
            and (c.c_name like '%${name}%' or c.c_address like '%${name}%' or c.c_tel like '%${name}%')
        </if>
    </sql>
    
    <!-- 查詢 -->
    <select id="find" parameterType="Map" resultType="Company">
        select <include refid="field"/>
        from company c
        where 1=1 <include refid="sql"/>
        order by c.c_id desc
    </select>
    
    <!-- 分頁查詢 -->
    <select id="findPage" parameterType="Map" resultType="Company">
        select <include refid="field"/>
        from company c
        where 1=1 <include refid="sql"/>
        order by c.c_id desc
        limit ${startIndex}, ${pageSize}
    </select>
    
    <!-- 查詢條數 -->
    <select id="findCount" parameterType="Map" resultType="Integer">
        select count(c.c_id)
        from company c
        where 1=1 <include refid="sql"/>
    </select>
    
    <!-- id查詢 -->
    <select id="findById" parameterType="Integer" resultType="Company">
        select <include refid="field"/>
        from company c
        where c.c_id = #{id}
    </select>
    
    <!-- 添加 -->
    <insert id="add" parameterType="Company">
        insert into company(
            c_name,
            c_address,
            c_tel
        )values(
            #{name},
            #{address},
            #{tel}
        )
    </insert>
    
    <!-- 刪除 -->
    <delete id="delete" parameterType="Integer">
        delete from company where c_id = #{id}
    </delete>
    
    <!-- 修改 -->
    <update id="update" parameterType="Company">
        update company
        <set>
            <if test="name != null">
                c_name = #{name},
            </if>
            <if test="address != null">
                c_address = #{address},
            </if>
            <if test="tel != null">
                c_tel = #{tel},
            </if>
        </set>
        where c_id = #{id}
    </update>
    
</mapper>

 

而後映射到mybatis-config.xml配置文件mybatis

 

 

我鏈接數據庫是運用spring配置文件來鏈接數據庫,運用sqlsessionFactorymvc

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
    <!-- 啓用Spring註解 -->
    <context:annotation-config/>
    
    <!-- 自動掃描註解類 -->
    <context:component-scan base-package="com.sdtg"/>
    
    <context:property-placeholder location="classpath:jdbc.properties" />
    
    <!-- 自動掃描Mapper接口 --> 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sdtg"/>
    </bean>
    
    <!-- 數據源 在spring裏面配置數據庫  -->
    <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean> 
    
    <!-- Sql Session工廠 --><!-- 映射到mybatis.xml文件-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/> 
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    
    <!-- Sql Session -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>
    
    <!-- hibernate 映射實體類裏面,用註解的方式實現自動建表的功能 -->
    <bean id="sessionFactory" name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.sdtg" />
        <property name="hibernateProperties">
            <props>
                <!-- Hibernate方言 -->
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <!-- 是否輸出Sql語句 -->
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <!-- 當前Session策略類 -->
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                <!-- 格式化Sql語句 -->
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <!-- 開啓後,Hibernate將收集有助於性能調節的統計數據 -->
                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                <!-- 自動建立數據庫表 -->
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            </props>
        </property>
    </bean>
    
    <!-- 事物 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

 補充:

service和控制層的源碼

package com.sdtg.contacts.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sdtg.contacts.bean.Company;
import com.sdtg.contacts.dao.CompanyDao;
import com.sdtg.utils.ConvertUtils;
import com.sdtg.utils.Page;

@Service //標註一個業務邏輯組件類
@Transactional
public class CompanyService {

    @Resource
    private CompanyDao dao;
    
    /**
     * 查詢
     * @param map
     * @return
     */
    public List<Company> find(Map<String, Object> map){
        try {
            
            return dao.find(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 分頁查詢
     * @param map
     * @return
     */
    public Page<Company> findPage(Map<String, Object> map){
        try {
            Page<Company> page = new Page<Company>();
            page.setTotalCount(dao.findCount(map));
            page.setCurrPage(ConvertUtils.stringToInteger(map.get("currPage").toString()));
            map.put("startIndex", page.getStartIndex());
            map.put("pageSize", page.getPageSize());
            page.setList(dao.findPage(map));
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * id查詢
     * @param id
     * @return
     */
    public Company findById(Integer id){
        try {
            return dao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 添加
     * @param company
     */
    public Boolean add(Company company){
        try {
            dao.add(company);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 刪除
     * @param id
     */
    public Boolean delete(Integer id){
        try {
            dao.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 修改
     * @param company
     */
    public Boolean update(Company company){
        try {
            dao.update(company);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

控制層:

package com.sdtg.contacts.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sdtg.contacts.bean.Company;
import com.sdtg.contacts.service.CompanyService;
import com.sdtg.system.service.OperateLogService;
import com.sdtg.utils.Page;

@Controller  //相似Struts的Action,標註一個控制器組件類
public class CompanyController {

    @Resource  //命名爲'setCompanyService'的方法被用來處理名爲'ompanyService'的屬性。
    private CompanyService companyService;
    
    @Resource
    private OperateLogService operateLogService;
    
    /**
     * 查詢公司
     * @param request
     * @param result
     * @param currPage
     * @param name
     * @return
     */
    @RequestMapping(value = "companyList") // 請求url地址映射,相似Struts的actiohn-mapping,直接將返回值返回到頁面
    public ModelAndView companyList(HttpServletRequest request, String result, String currPage, String name){
        // request和response沒必要非要出如今方法中,若是用不上的話能夠去掉
        // 參數的名稱是與頁面控件的name相匹配,參數類型會自動被轉換
        System.out.println("進入查詢功能");
        
        ModelAndView mav = new ModelAndView();  
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name); //在jsp頁面中可直經過${name}得到到值, map.put()至關於request.setAttribute方法。
        map.put("currPage", currPage != null ? currPage : 1);
        
        Page<Company> page = companyService.findPage(map);
        mav.addObject("companyList",page.getList());
        System.out.println("進入分頁查詢");
        mav.addObject("page",page);
        
        mav.addObject("result",result);//增刪改的結果
        //返回查詢條件
        mav.addObject("name",name);
        
        mav.setViewName("contacts/company");
        return mav;  //
    }
    
    /**
     * 添加公司
     * @return
     */
    @RequestMapping(value = "companyAdd")
    public ModelAndView companyAdd(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("contacts/company_form");
        return mav;
    }
    
    /**
     * 修改公司
     * @param id
     * @return
     */
    @RequestMapping(value = "companyUpdate")
    public ModelAndView companyUpdate(Integer id){
         // 一樣支持參數爲表單對象,相似於Struts的ActionForm,Integer id不須要任何配置,直接寫便可
        ModelAndView mav = new ModelAndView(); // 採用重定向方式跳轉頁面
        mav.addObject("company", companyService.findById(id));
        mav.setViewName("contacts/company_form"); 
        return mav;
    }
    
    /**
     * 保存公司
     * @param request
     * @param company
     * @return
     */
    @RequestMapping(value = "companySave")
    public ModelAndView companySave(HttpServletRequest request, Company company){
        ModelAndView mav = new ModelAndView();
        Boolean flag;
        if(null == company.getId()){//添加
            flag = companyService.add(company);
            operateLogService.add(request, "添加公司:"+company.getName());
        } else {//修改
            flag = companyService.update(company);
            operateLogService.add(request, "修改公司:id="+company.getId());
        }
        mav.setViewName("redirect:companyList.do?result="+flag);
        return mav;
    }
    
    /**
     * 刪除公司
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "companyDelete")
    public ModelAndView companyDelete(HttpServletRequest request, Integer id){
        ModelAndView mav = new ModelAndView();
        Boolean flag = companyService.delete(id);
        if(flag){
            operateLogService.add(request, "刪除公司:id="+id);
        }
        mav.setViewName("redirect:companyList.do?result="+flag);
        return mav;
    }
    
    
    
    
}
相關文章
相關標籤/搜索