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);
        }
    }
}

你可能感兴趣的:(mybatis)