将长内容分割,用双主键进行存储

有时候需要保存的内容很长很长,数据库的一个字段无法全部存完,我们就可以使用双主键,将内容分割后再进行存储

 

//存储内容的主要方法
//Entity为假设的,使用双主键的实体,其主键实体为EntityPK
//content为需要进行存储的内容
private List<Entity> genEntityList(Entity entity,String content) {
  List<Entity > entity= new ArrayList<Entity >();
  Map<String, Object> query=new HashMap<String, Object>();
  // 将字符串按4000的长度进行分割
  int maxLen = 1300;
  // 需要分割的次数
  int twices = content.length() / maxLen;
  twices++;
  //getEntityId方法用于获取id(插入方法中就不要配置生成id了)
  //语句如下:SELECT SEQ_ENTITY.NEXTVAL FROM DUAL
  List idlist=entityService.queryList("getEntityId", null);
  String id=idlist.get(0).toString();
  for (int i = 0; i < twices; i++) {
    int beginIdx = i * maxLen;
    int endIdx = (i + 1) * maxLen;
    String EntCon = content.substring(beginIdx, endIdx > content.length() ? content.length() : endIdx);
    Entity bEntity  = newEntity ();
    EntityPK pk = newEntityPK ();
    pk.setId(id);
    pk.setSeqnum(i + "");
    bEntity .setPk(pk);
    bEntity .setEntCon(EntCon );
    entity.add(bCfgMessageIn);
  }

  return entity;
}

 

    //在方法中进行调用
    //相关表中用一个字段关联一下Entity的Id
    public void setContent() {
  ……
  //do something   List<Entity> list=genEntityList(entity, content);   entityService.insertInBatch(list); }

 

 

//dao中的insertInBatch方法
@Override
public int insertInBatch(List<T> entityList) {
  if (entityList == null || entityList.isEmpty())
  return 0;
  int i=0;
  for (T entity : entityList) {
    i+=this.insert(entity);
   }
  return i;
}
原文地址:https://www.cnblogs.com/IceBlueBrother/p/8421701.html