虽然项目经历觉得这样做不妥,但还是觉得有必要记录一下。
主要思路就是:
数据表名格式在自己规定好的,如:sys_log_2018,2018是获取当前年份;
添加数据时会判断数据库是否存在这张表,如果存在,则会添加数据,如果不存在,则会根据年份重新创建一个新的物理表;
创建表的代码如下
/** * 创建表 * @param tableName */ public void createTmpTable(@Param(value="tableName")String tableName);
创建表的sql如下:
<update id="createTmpTable" parameterType="string"> CREATE TABLE ${tableName}( id VARCHAR2(64) not null, log_type VARCHAR2(64), title NVARCHAR2(500), create_by VARCHAR2(64), create_date TIMESTAMP(6), remote_addr VARCHAR2(255), user_agent VARCHAR2(255), request_uri VARCHAR2(255), method VARCHAR2(5), params CLOB, exception CLOB, operate_type VARCHAR2(64), content CLOB, PRIMARY KEY (id) ) </update>
查询表名:
public List<String> findAllTableNames();
<select id="findAllTableNames" resultType="String"> <![CDATA[ select table_name from user_tables ]]> </select>
public static void saveLog(HttpServletRequest request, Log log){ LogService logService = (LogService) ContextLoader.getCurrentWebApplicationContext() .getBean("logService");
//查询所有表名 List<String> list = logService.findAllTableNames(); String tableName = "sys_log_" + DateUtils.getYear(); if (!list.contains(tableName.toUpperCase())) { logService.createTmpTable(tableName); } User user = UserUtils.getUser(); if (user != null && user.getId() != null){ log.setCreateBy(user); log.setRemoteAddr(com.thinkgem.jeesite.common.utils.StringUtils.getRemoteAddr(request)); log.setUserAgent(request.getHeader("user-agent")); log.setRequestUri(request.getRequestURI()); log.setParams(request.getParameterMap()); log.setMethod(request.getMethod()); log.setCreateDate(user.getLoginDate()); log.preInsert(); log.setTableName(tableName); logDao.insert(log); } }