首页 > 代码库 > hibernate分表保存日志

hibernate分表保存日志

@Service("accessLogService")
@Transactional
public class LogMessageServiceImpl extends BaseDaoServiceImpl<AccessLogMessage,Long> implements LogMessageService{
 @Autowired
 SplitHibernateInterceptor splitInter;
 @Autowired
 public BaseDaoImpl<AccessLogMessage> baseDao;
 /**
  * 根据当前月份
  */
 @Override
 public void addLog(AccessLogMessage message) {
  //要拦截的目标数据库名称
  splitInter.setTargetTableName("accesslog_message");
  //月份从0计算
  int month = Calendar.getInstance().get(Calendar.MONTH);
  if(month==0){
   //1月份
   baseDao.save(message);
  }else{
   splitInter.setSubTableName("accesslog_message"+month);
   SessionFactory sf= baseDao.getSessionFactory();
   Session session = sf.openSession(splitInter);
   try{
    session.save(message);
   }finally{
    session.close();
   }
  }
  
 }
}

 

@Service("splitInter")
public class SplitHibernateInterceptor extends EmptyInterceptor {
 private static final long serialVersionUID = 2293562313992510554L;

 private String targetTableName;// 目标母表名
 private String subTableName;// 操作子表名 ,与目标结构一样

 public SplitHibernateInterceptor() {
 }

 public java.lang.String onPrepareStatement(java.lang.String sql) {
  sql = sql.toLowerCase();
  sql = sql.replaceAll(targetTableName, subTableName);
  return sql;

 }

 public String getTargetTableName() {
  return targetTableName;
 }

 public void setTargetTableName(String targetTableName) {
  this.targetTableName = targetTableName;
 }

 public String getSubTableName() {
  return subTableName;
 }

 public void setSubTableName(String subTableName) {
  this.subTableName = subTableName;
 }

}

 

 

@Component("baseDaoService")
@Transactional
public class BaseDaoServiceImpl<T, K extends Serializable> implements
  BaseDaoService<T, K> {

 @Autowired
 public ExtendBaseDao<T, K> extendBaseDao;

 @Override
 public void add(T t) {
  extendBaseDao.save(t);
 }

 @Override
 public void delete(T t) {
  extendBaseDao.delete(t);
 }

 @Override
 public void update(T t) {
  extendBaseDao.update(t);
 }

 @Override
 public T get(Class<T> entityClass, K k) {
  return extendBaseDao.get(entityClass, k);
 }

 @Override
 public void deleteByHql(String hql ,Object... objects) {
  extendBaseDao.delete(hql, objects);
 }

 @Override
 public List<T> query(String hql, Object... objects) {
  return extendBaseDao.list(hql, objects);
 }

 @Override
 public void marge(T t) {
  extendBaseDao.merge(t);
 }

}

 

@Entity
@Table(name = "ACCESSLOG_MESSAGE")
public class AccessLogMessage {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private Long id;
 @Column(name = "requestURI", length = 250)
 private String requestURI;
 
 @Column(name = "requestTime", length = 30)
 private String requestTime;
 @Column(name = "requestParams", length = 1000)
 private String requestParams;
 @Column(name = "userName", length = 32)
 private String userName;