• MyBatis的应用


    a)首先先导入固定的jar包

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

    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>
         <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>

    2、创建对应的实体对象

    对应的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

    3、创建接口和对应的定义操作company表的sql映射文件Company.xml(以company为例)

    接口提供简单的增删改查数据的信息

    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语句进行对数据信息的增删改查

    <?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配置文件

    我连接数据库是运用spring配置文件来连接数据库,运用sqlsessionFactory

    <?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;
        }
        
        
        
        
    }
  • 相关阅读:
    ftp上传工具类&FTPClient通过代理连接到FTP服务器
    JS判断闰年与获取月份天数
    SpringBoot文件上传文件大小限制The field file exceeds its maximum permitted size of 1048576 bytes.
    JSON.parse解析json字符串包含 回车换行符报错
    JS解决加减乘除浮点类型丢失精度问题
    Mysql连接异常java.sql.SQLException: The server time zone value '?й???????' is unrecognized or represents more than one time zone.
    Springboot基于Guava+自定义注解实现IP或自定义key限流 升级版
    Centos7设置默认进入图形界面和命令行界面
    第一节 RabbitMQ入门及安装
    第三节 Kafka性能优化实践
  • 原文地址:https://www.cnblogs.com/zhoudi/p/6120847.html
Copyright © 2020-2023  润新知