`
y806839048
  • 浏览: 1117201 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

mybatise 应用

 
阅读更多
/////mybatise
spring中集成
OperationLog.java实体 
OperationLog.xml 配xml,sql与类没有明显的绑定关系,只是一般一个类一个,有体现的话在标签内
OperationLogLS.java*ls 找xml 方法为xml中标签

        OperationLogRest    operationLogLS.insertOne(operationLog);


====================================================
spring中集成mybatise

sqlConfiguration.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="false" />
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false" />
<setting name="multipleResultSetsEnabled" value="false" />
<setting name="useColumnLabel" value="true" />
<setting name="useGeneratedKeys" value="false" />
<setting name="autoMappingBehavior" value="PARTIAL" />
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="defaultStatementTimeout" value="2000" />
</settings>

</configuration>


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:sqlConfiguration.xml" />//总配置文件
    <property name="mapperLocations" value="classpath*:com/certusnet/nfv/**/mapper/*.xml" />//各个实体对应文件OperationLog.xml
  </bean>
 
 
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
scope="prototype" autowire="constructor">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

<bean id="baseService" class="com.certusnet.nfv.mano.BaseService"
scope="prototype" autowire="byName" abstract="true">
<property name="sqlSession" ref="sqlSession" />
</bean>

<bean id="operationLogLS" class="com.certusnet.nfv.mano.common.logic.OperationLogLS" scope="prototype"
    autowire="byName" parent="baseService">
  </bean>





========================================================


OperationLog.java

package com.certusnet.nfv.mano.common.model;

public class OperationLog
{
    private long id = 0;
    private String userId = null;
    private String eventId = null;
    private String subsystem = null;
    private String operateType = null;
    private String requestContent = null;
    private String responseStatus = null;
    private String responseContent = null;
    private String createTime = null;
    private String eventName;
   
   
    public String getEventName() {
return eventName;
}

public void setEventName(String eventName) {
this.eventName = eventName;
}

public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getUserId()
    {
        return userId;
    }

    public void setUserId(String userId)
    {
        this.userId = userId;
    }

    public String getEventId()
    {
        return eventId;
    }

    public void setEventId(String eventId)
    {
        this.eventId = eventId;
    }

    public String getSubsystem()
    {
        return subsystem;
    }

    public void setSubsystem(String subsystem)
    {
        this.subsystem = subsystem;
    }

    public String getOperateType()
    {
        return operateType;
    }

    public void setOperateType(String operateType)
    {
        this.operateType = operateType;
    }

    public String getRequestContent()
    {
        return requestContent;
    }

    public void setRequestContent(String requestContent)
    {
        this.requestContent = requestContent;
    }

    public String getResponseStatus()
    {
        return responseStatus;
    }

    public void setResponseStatus(String responseStatus)
    {
        this.responseStatus = responseStatus;
    }
   
    public void setResponseStatus(ResponseStatus responseStatus)
    {
        this.responseStatus = responseStatus.getValue();
    }

    public String getResponseContent()
    {
        return responseContent;
    }

    public void setResponseContent(String responseContent)
    {
        this.responseContent = responseContent;
    }
   
    public void setResponseContent(String content, Throwable e)
    {
        StringBuffer sbContent = new StringBuffer(content);
        sbContent.append("\r\n").append(e.getMessage());
       
        for(StackTraceElement element : e.getStackTrace())
        {
            sbContent.append("\r\n").append(element.toString());
        }
       
        responseContent = new String(sbContent);
    }

    public String getCreateTime()
    {
        return createTime;
    }

    public void setCreateTime(String createTime)
    {
        this.createTime = createTime;
    }

    private String startTime = null;
    private String endTime = null;

    public String getStartTime()
    {
        return startTime;
    }

    public void setStartTime(String startTime)
    {
        this.startTime = startTime;
    }

    public String getEndTime()
    {
        return endTime;
    }

    public void setEndTime(String endTime)
    {
        this.endTime = endTime;
    }
   
    public enum ResponseStatus
    {
        SUCCESS("ok"), FAILURE("failed");
       
        private String value = null;
       
        private ResponseStatus(String value)
        {
            this.value = value;
        }
       
        public String getValue()
        {
            return value;
        }
    }
}


==================================================


OperationLog.xml
namespace="com.certusnet.nfv.mano.common.mapper.OperationLog"这个是xml路径不是类

由于不是有明显改的对应关系,所以实体类更类似于bo,可以是组合型的bo


<?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.certusnet.nfv.mano.common.mapper.OperationLog">
  <sql id="allColumns">
    o.id,user_id as userId,ename.event_id as eventId,subsystem,operate_type as operateType,request_content as requestContent,
    response_status as responseStatus,response_content as responseContent,create_time as createTime,ename.event_name as eventName
  </sql>

  <sql id="dynamicKeyConditions">
    <where>
      <trim suffixOverrides="and">
        <if test="id > 0">id=#{id} and</if>
        <if test="eventId != null">event_id=#{eventId} and</if>
        <if test="startTime != null">create_time&gt;=#{startTime} and</if>
        <if test="endTime != null">create_time&lt;=#{endTime} and</if>
       </trim>
    </where>
  </sql>
 
  <sql id="pageConditions">
    <where>
      <trim suffixOverrides="and">
        <if test="userId != null">user_id=#{userId} and</if>
        <if test="eventId != null">event_id=#{eventId} and</if>
        <if test="subsystem != null">subsystem=#{subsystem} and</if>
        <if test="operateType != null">operate_type=#{operateType} and</if>
        <if test="startTime != null">create_time&gt;=#{startTime} and</if>
        <if test="endTime != null">create_time&lt;=#{endTime} and</if>
       </trim>
    </where>
   
    <if test="orderField != null">order by ${orderField}</if>
    <if test="orderType == 1">desc</if>
    <if test="startNum >= 0 and pageSize > 0">limit ${startNum}, ${pageSize}</if>
  </sql>

  <select id="selectOne" parameterType="com.certusnet.nfv.mano.common.model.OperationLog" resultType="com.certusnet.nfv.mano.common.model.OperationLog">
    select <include refid="allColumns" /> from operation_log <include refid="dynamicKeyConditions" />
  </select>

  <!-- <select id="selectList" parameterType="long" resultType="com.certusnet.nfv.mano.common.model.OperationLog">
    select <include refid="allColumns" /> from operation_log <include refid="dynamicKeyConditions" />
  </select> -->
  <select id="selectList" parameterType="long" resultType="com.certusnet.nfv.mano.common.model.OperationLog">
    select <include refid="allColumns" /> from operation_log o LEFT JOIN event_id_name ename on o.event_id=ename.event_id  <include refid="dynamicKeyConditions" />
  </select>
  <select id="selectPage" resultType="com.certusnet.nfv.mano.common.model.OperationLog">
    select <include refid="allColumns" /> from operation_log o LEFT JOIN event_id_name ename on o.event_id=ename.event_id   <include refid="pageConditions" />
  </select>
 
  <select id="countAll" resultType="int">
    select count(id) from operation_log <include refid="pageConditions" />
  </select>
 
  <sql id="dynamicInsertColumns">
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id > 0">id,</if>
      <if test="userId != null">user_id,</if>
      <if test="eventId != null">event_id,</if>
      <if test="subsystem != null">subsystem,</if>
      <if test="operateType != null">operate_type,</if>
      <if test="requestContent != null">request_content,</if>
      <if test="responseStatus != null">response_status,</if>
      <if test="responseContent != null">response_content,</if>
      <if test="createTime != null">create_time</if>
    </trim>
  </sql>

<sql id="dynamicInsertColumnsEvent">
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id > 0">id,</if>
      <if test="eventId != null">event_id,</if>
      <if test="eventName != null">event_name</if>
    </trim>
  </sql>

  <sql id="dynamicInsertValues">
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id > 0">#{id},</if>
      <if test="userId != null">#{userId},</if>
      <if test="eventId != null">#{eventId},</if>
      <if test="subsystem != null">#{subsystem},</if>
      <if test="operateType != null">#{operateType},</if>
      <if test="requestContent != null">#{requestContent},</if>
      <if test="responseStatus != null">#{responseStatus},</if>
      <if test="responseContent != null">#{responseContent},</if>
      <if test="createTime != null">#{createTime},</if>
    </trim>
  </sql>

<sql id="dynamicInsertValuesEvent">
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id > 0">#{id},</if>
      <if test="eventId != null">#{eventId},</if>
      <if test="eventName != null">#{eventName},</if>
    </trim>
  </sql>

  <insert id="insertOne" parameterType="com.certusnet.nfv.mano.common.model.OperationLog">
    insert into operation_log <include refid="dynamicInsertColumns" /> values <include refid="dynamicInsertValues" />
    <selectKey resultType="long" order="AFTER" keyProperty="id">
      <if test="id &lt;= 0">select last_insert_id() as id</if>
      <if test="id > 0">select #{id} as id</if>
    </selectKey>
  </insert>
 
  <insert id="insertEvent" parameterType="com.certusnet.nfv.mano.common.model.EventNameId">
    insert into event_id_name <include refid="dynamicInsertColumnsEvent" /> values <include refid="dynamicInsertValuesEvent" />
<selectKey resultType="long" order="AFTER" keyProperty="id">
      <if test="id &lt;= 0">select last_insert_id() as id</if>
      <if test="id > 0">select #{id} as id</if>
    </selectKey>
  </insert>
 
</mapper>




==================================================================


OperationLogLS.java


package com.certusnet.nfv.mano.common.logic;

import java.util.List;

import com.certusnet.nfv.mano.BaseService;
import com.certusnet.nfv.mano.Constants;
import com.certusnet.nfv.mano.common.logicapi.IOperationLogLS;
import com.certusnet.nfv.mano.common.model.EventNameId;
import com.certusnet.nfv.mano.common.model.OperationLog;
import com.certusnet.nfv.mano.common.pojo.OperLogQuery;

public class OperationLogLS extends BaseService implements IOperationLogLS
{
//配置文件路径
    private static final String path = Constants.MAPPER_COMMON + OperationLog.class.getSimpleName();
//getSqlSession().selectList   sqlsession这些方法的选择根据操作类型和返回类型path + ".selectOne(对应xml中的路径)"
           
    public OperationLog selectOne(OperationLog parameter) throws Exception
    {
        if((parameter == null) || (parameter.getId() <= 0))
        {
            throw new NullPointerException("Indexed fields are all null");
        }

        return getSqlSession().selectOne(path + ".selectOne", parameter);
    }

    public List<OperationLog> selectMore(OperationLog parameter) throws Exception
    {
        return getSqlSession().selectList(path + ".selectList", parameter);
    }

    public int insertOne(OperationLog parameter) throws Exception
    {
        if(parameter == null)
        {
            throw new NullPointerException("Empty parameter");
        }
       
        if(parameter.getCreateTime() == null)
        {
            parameter.setCreateTime(Constants.formatTimeStamp());
        }

        return getSqlSession().insert(path + ".insertOne", parameter);
    }
   
    public List<OperationLog> selectPage(OperLogQuery operlogQuery) throws Exception
    {
        return getSqlSession().selectList(path + ".selectPage", operlogQuery);
    }
   
    public int countAll(OperLogQuery operlogQuery) throws Exception
    {
    return getSqlSession().selectOne(path + ".countAll", operlogQuery);
    }

@Override
public int insertEventOne(EventNameId parameter) throws Exception {
        if(parameter == null)
        {
            throw new NullPointerException("Empty parameter");
        }
       

        return getSqlSession().insert(path + ".insertEvent", parameter);
    }
}




package com.certusnet.nfv.mano;

import org.apache.ibatis.session.SqlSession;

/**
* 数据库操作基类
*/
public abstract class BaseService(供注入sqlsession)
{
    private SqlSession sqlSession;

    public SqlSession getSqlSession()
    {
        return sqlSession;
    }

    public void setSqlSession(SqlSession sqlSession)
    {
        this.sqlSession = sqlSession;
    }
}


package com.certusnet.nfv.mano.common.logicapi;

import java.util.List;

import com.certusnet.nfv.mano.common.model.EventNameId;
import com.certusnet.nfv.mano.common.model.OperationLog;
import com.certusnet.nfv.mano.common.pojo.OperLogQuery;

public interface IOperationLogLS(供面向接口编程,外界调用)
{
    public OperationLog selectOne(OperationLog parameter) throws Exception;
   
    public List<OperationLog> selectMore(OperationLog parameter) throws Exception;

    public int insertOne(OperationLog parameter) throws Exception;
   
    public List<OperationLog> selectPage(OperLogQuery operlogQuery) throws Exception;
   
    public int countAll(OperLogQuery operlogQuery) throws Exception;
   
    public int insertEventOne(EventNameId parameter) throws Exception;
}



//////////接口中应用:
operationLogLS.insertOne(operationLog);

//应用
@Component
@Path("/")//接着web.xml中设置的rest的第二层路径
public class OperationLogRest
{
    private static Logger LOG = Logger.getLogger(OperationLogRest.class);
    @Autowired(required=true)
    private IOperationLogLS operationLogLS;
@POST
    @Path("logs/generation")
    @Produces(ContentType.APPLICATION_JSON_UTF_8)
    @Consumes(ContentType.APPLICATION_JSON_UTF_8)
    public long saveOperationLog(@Context HttpServletRequest request) throws ManoException
    {
        try
        {
            OperationLog operationLog = new OperationLog();
            operationLog.setEventId(request.getParameter("Event-Id"));
            operationLog.setOperateType(request.getParameter("Operate-Type"));
            operationLog.setRequestContent(request.getParameter("Request-Content"));
            operationLog.setSubsystem(request.getParameter("Subsystem"));
            operationLog.setUserId(request.getParameter("User-Id"));
            operationLog.setResponseContent(request.getParameter("Response-Content"));
            operationLog.setResponseStatus(request.getParameter("Response-Status"));
            operationLogLS.insertOne(operationLog);
            return operationLog.getId();
        }
        catch (Exception ex)
        {
            LOG.error(ex.getMessage(), ex);
            throw new ManoException(ex);
        }
    }
}
分享到:
评论

相关推荐

    mybatise jar

    在 Java Web 开发中,Spring 框架被广泛使用,它提供了全面的企业级应用开发解决方案,包括事务管理、数据访问、依赖注入等。整合 MyBatis 与 Spring,可以构建出更加灵活且易于维护的项目结构。 MyBatis-Spring 是...

    springmvc+mybatise代码

    SpringMVC和MyBatis是两个非常流行的Java开发框架,它们在企业级Web应用中有着广泛的应用。SpringMVC作为Spring框架的一部分,主要用于处理HTTP请求和响应,而MyBatis则是一个优秀的持久层框架,专注于数据库操作。...

    mybatise和spring框架

    MyBatis和Spring框架是Java开发中非常重要的两个组件,它们在企业级应用开发中扮演着核心角色。MyBatis是一个优秀的持久层框架,它解决了Java中的数据访问问题,而Spring则是一个全面的企业级应用框架,提供了依赖...

    spring+mybatise 简单架构

    【Spring+MyBatis简单架构】是Web开发中一种常见的技术组合,主要应用于构建轻量级的企业级应用。Spring作为一款全面的Java企业级应用框架,提供了依赖注入、AOP(面向切面编程)、事务管理等多种功能,而MyBatis则...

    springMVC+mybatise+maven的eclipse框架

    【标题】"springMVC+mybatise+maven的eclipse框架" 描述了一个基于Java的Web开发架构,这是在Eclipse集成开发环境下构建的一种高效、模块化且可维护的项目结构。在这个框架中,Spring MVC负责处理HTTP请求并协调应用...

    struts2+spring+mybatise实现PhoneBook电话簿信息管理系统

    综上所述,"struts2+spring+mybatise实现PhoneBook电话簿信息管理系统"是一个涵盖了前端交互、后端服务和数据存储的完整项目,展示了Java EE开发中的典型技术和实践。这个项目不仅锻炼了开发者对三大框架的理解和...

    Spring Cloud+mybatise + mysql 自动生成代码工具

    "Spring Cloud+mybatise + mysql 自动化代码生成工具"是这样一种解决方案,它能够帮助开发者按照预设规则自动生成常见的Controller、Service以及mapping配置文件等基础类,从而显著提升开发效率。 首先,我们来详细...

    Java程序员面试,MyBatise常见面试27道必问题

    1. 基于 SQL 语句编程,相当灵活,不会对应用程序或者数据库的现有设计造成任何影响,SQL 写在 XML 里,解除 sql 与程序代码的耦合,便于统一管理。 2. 与 JDBC 相比,减少了 50%以上的代码量,消除了 JDBC 大量冗余...

    springboot + mybatise+druid多源静态数据库访问

    首先,Spring Boot是基于Spring框架的高度模块化、简化配置的开发工具,它简化了初始化、配置和运行Spring应用的过程。在Spring Boot中,我们可以通过声明式配置或者Java配置来管理数据源。 MyBatis是一个轻量级的...

    struts2+spring+mybatise实现电话簿信息管理网站(包括数据库设计及测试用例)

    Struts2、Spring和MyBatis是Java Web开发中常用的三大框架,它们组合起来可以构建高效、可维护的Web应用程序。在这个"电话簿信息管理网站"项目中,开发者利用这三者的优势,实现了对电话簿数据的存储、查询、更新和...

    mybatise基于xml配置的实现增删改查的一个完整项目

    MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在本项目中,我们将深入探讨如何使用 ...在实际开发中,你可以根据自己的需求调整 SQL 语句,添加更复杂的业务逻辑,以满足各种应用场景。

    mybatis-generator自动生成代码

    在实际应用中,MBG不仅可以生成基本的CRUD操作,还可以根据配置生成复杂的查询方法,比如分页查询、多条件组合查询等。通过合理配置,MBG可以适应各种项目需求,使得代码更加规范,开发流程更加高效。 总结起来,...

    maven+SpringMvc+mybatis实例

    这个实例将帮助你理解如何构建一个完整的Java Web应用程序,从依赖管理到业务逻辑处理。 **Maven** 是一个项目管理和构建工具,它的核心功能是管理项目的依赖关系。在本实例中,你需要配置Maven环境以运行项目。这...

    SpringMVC Activiti mysql

    SpringMVC、Activiti 和 MySQL 是企业级应用开发中常用的技术栈,它们分别在不同的领域发挥着关键作用。本文将详细介绍这些技术以及如何将它们整合到一个项目中。 首先,让我们了解一下这三个技术的基础: 1. **...

    增删改查demo项目,eclipse

    在【压缩包子文件的文件名称列表】中,只有一个文件名为"myBatise001",这可能是项目的主要源代码包或者是一个重要的模块。在这个包中,我们可以预期找到以下内容: 1. **Mapper接口**:这些接口定义了数据库操作的...

    contentManagerSystem.rar

    其核心特性包括自动配置、内嵌Web服务器(如Tomcat)以及“起步依赖”等,使得开发者能够快速地创建一个独立运行的、生产级别的Java应用。 二、MyBatis介绍与集成 MyBatis是一个优秀的持久层框架,它支持定制化SQL...

    超快mybatis3.2.3

    MyBatis 3.2.3 是一个流行的Java持久层框架,它简化了数据库操作,提供了灵活的映射机制,使得开发人员能够更方便地处理SQL、存储过程...通过理解并熟练运用这些知识点,开发人员可以构建出高性能、易维护的Java应用。

    Spring Boot整合MyBatis连接Oracle数据库的步骤全纪录

    这将涉及几个关键步骤,确保你的应用程序能够正确地读取和操作Oracle数据库中的数据。 首先,我们需要在Spring Boot项目中添加MyBatis和Oracle数据库驱动的依赖。在你的`pom.xml`文件中,你需要引入以下两个依赖: ...

Global site tag (gtag.js) - Google Analytics