批量添加数据库操作代码(代码+sql+postman测试示例)

该文章展示了一个使用JavaSpringBoot框架,通过控制器、服务、Mapper接口来批量添加People数据到MySQL数据库的过程。数据表结构、实体类定义、RESTAPI接口、MapperSQL语句以及Postman的测试用例都进行了详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)创建数据表 People

CREATETABLE `people` (
  `id` int(10) NOTNULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(10) DEFAULT NULL,
  `height` double(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=gb2312

(2)创建实体类People

@Data//有这个注解就不用写get、set、toString方法了,前提是要引入lombok依赖
public class People {
    private String name;
    private Integer id;
    private Integer age;
    private Double height;
}

(3)controller层代码

@RestController
@RequestMapping("/people")
public class PeopleController{ 
    @Autowired
    private PeopleService peopleService;
/**
     * 批量添加数据
     * @param people
     * @return int返回形式可以自己定
     */
    @PostMapping("/addList")
    public int addList(@RequestBody List<People> people){
        return peopleService.addList(people);
    }
}

(4)service层代码

/**
 * @author xxx
 * @version $Id: PeopleService.java, v 0.1 2022-07-11 14:51
 */
public interface PeopleService {
    int addList(List<People> people);
}
​
/**
* @author xxx
* @version $Id: PeopleServiceImpl.java, v 0.1 2022-07-11 14:52
*/
@Service
public class PeopleServiceImpl implements PeopleService {
    @Resource
    private PeopleMapper peopleMapper;
​
    @Override
    public int addList(List<People> people) {
        return peopleMapper.addList(people);
    }
}

(5)Mapper层代码

/**
 * @author xxx
 * @version $Id: PeopleMapper.xml.java, v 0.1 2022-07-11 14:54
 */
@Mapper
public interface PeopleMapper {
    
    int addList(@Param("list") List<People> people);
}

(6)SQL语句

 <insert id="addList">
        insert into people(id,name,age,height)
        values
        <foreach collection="list" item="item" open="(" separator="),(" close=")">
            #{item.id},#{item.name},#{item.age},#{item.height}
        </foreach>
    </insert>

(7)postman自测(注意入参json格式)

[{
        "id": 10,
        "name": "张三",
        "age": "22",
        "height": "185"
​
    },{
        "id": 9,
        "name": "李四",
        "age": "24",
        "height": "188"
​
    }]

(8)结果与演示

结果:

<think>嗯,用户需要的是用SpringBoot和MyBatis实现法典导入,并且要拆分章节和关键词,然后存到数据库。同时还要支持Word和PDF的解析。我得先理清楚整个流程需要哪些步骤。 首先,用户的需求是上传Word和PDF文件,解析里面的内容,提取章节和关键词,然后存储到数据库。可能需要用到文件解析的库,比如Apache POI处理Word,PDFBox处理PDF。然后MyBatis做数据持久化,SpringBoot搭建整体框架。 接下来,我需要考虑项目结构。通常SpringBoot项目会有controller、service、dao层,还有实体类。用户提到了法典、章节、关键词,所以可能需要三个实体类:Code(法典)、Chapter(章节)、Keyword(关键词)。每个实体对应数据库的表,可能有外键关联。 然后,依赖包方面,除了SpringBoot Starter Web和MyBatis,还需要MyBatis Plus简化操作。另外,Apache POI和PDFBox是必须的。可能需要添加这些依赖到pom.xml里。 文件解析部分,对于Word文档,用POI的XWPFDocument来读取段落,提取章节。可能需要正则表达式来匹配章节标题,比如“第一章”、“第一节”这样的格式。PDF解析的话,PDFBox的PDFTextStripper可以提取文本内容,同样用正则表达式处理章节结构。 关键词拆分可能需要用到分词工具,比如IK Analyzer或者HanLP,但用户可能希望自己指定关键词,或者有特定的拆分规则。这里可能需要用户自定义逻辑,比如从段落中提取特定词汇,或者根据某种算法处理。 数据库存储部分,MyBatis Plus的BaseMapper可以简化CRUD操作。需要配置数据源,确保连接数据库正常。可能还要处理事务,比如在插入法典时同时插入章节和关键词,需要用到@Transactional注解。 代码示例部分,需要给出实体类、Mapper接口、Service层的解析和存储逻辑,以及Controller的文件上传接口。注意文件上传要处理MultipartFile,并调用解析服务。 可能遇到的问题包括文件解析的性能,大文件处理,以及数据库批量插入优化。MyBatis Plus在处理批处理时可能需要额外配置,尤其是对于SQL Server,但用户提到的是通用情况,可能用默认配置即可。 测试方面,可能需要用Postman上传文件,查看是否正确解析并存储到数据库。同时,异常处理也要考虑,比如文件格式不支持,解析错误等,返回相应的提示信息。 最后,用户可能需要完整的代码示例,所以需要提供各个层的关键代码片段,并说明依赖包。同时,回答中要引用之前提到的MyBatis Plus处理批处理的问题,指出可能需要额外注意的地方。</think># SpringBoot+MyBatis实现法典文档解析存储方案 ## 一、技术架构设计 1. 文档解析层:Apache POI处理Word(.docx),PDFBox解析PDF 2. 文本处理层:正则表达式提取章节结构,HanLP分词工具处理关键词 3. 数据持久层:MyBatis-Plus 3.5.1 + MySQL 8.0 4. 服务层:SpringBoot 2.7.x ## 二、核心代码实现 ### 1. Maven依赖配置(pom.xml片段) ```xml <!-- 文档解析 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.2</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.27</version> </dependency> <!-- 文本处理 --> <dependency> <groupId>com.hankcs</groupId> <artifactId>hanlp</artifactId> <version>portable-1.8.4</version> </dependency> <!-- 数据持久化 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> ``` ### 2. 实体类定义 ```java // 法典实体 @Data @TableName("legal_code") public class LegalCode { @TableId(type = IdType.AUTO) private Long id; private String codeName; private String fileType; private LocalDateTime createTime; } // 章节实体 @Data @TableName("code_chapter") public class CodeChapter { @TableId(type = IdType.AUTO) private Long id; private Long codeId; private String chapterTitle; private String content; private Integer sortOrder; } // 关键词实体 @Data @TableName("code_keyword") public class CodeKeyword { @TableId(type = IdType.AUTO) private Long id; private Long chapterId; private String keyword; private Integer frequency; } ``` ### 3. 文件解析服务 ```java @Service public class DocumentParserService { // Word文档解析 public List<ChapterContent> parseWord(MultipartFile file) throws IOException { XWPFDocument doc = new XWPFDocument(file.getInputStream()); List<ChapterContent> chapters = new ArrayList<>(); // 正则匹配章节标题(示例:第一章、第一节等) Pattern pattern = Pattern.compile("^第[一二三四五六七八九十]+章"); ChapterContent currentChapter = null; for (XWPFParagraph p : doc.getParagraphs()) { String text = p.getText(); if (pattern.matcher(text).find()) { if (currentChapter != null) { chapters.add(currentChapter); } currentChapter = new ChapterContent(); currentChapter.setTitle(text); } else if (currentChapter != null) { currentChapter.addContent(text); } } return chapters; } // PDF解析 public List<ChapterContent> parsePdf(MultipartFile file) throws IOException { PDDocument document = PDDocument.load(file.getInputStream()); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(document); // 章节解析逻辑与Word类似 return parseTextStructure(text); } } ``` ### 4. 关键词提取服务 ```java @Service public class KeywordService { public List<String> extractKeywords(String text) { List<String> keywords = new ArrayList<>(); List<Term> termList = HanLP.segment(text); for (Term term : termList) { // 过滤名词性词汇(可根据需求扩展) if (term.nature.toString().startsWith("n")) { keywords.add(term.word); } } return keywords.stream() .distinct() .collect(Collectors.toList()); } } ``` ### 5. 数据存储服务 ```java @Service @Transactional public class CodeImportService { @Autowired private LegalCodeMapper codeMapper; @Autowired private CodeChapterMapper chapterMapper; @Autowired private CodeKeywordMapper keywordMapper; public void importCode(MultipartFile file) throws IOException { // 解析文档 List<ChapterContent> chapters = documentParser.parse(file); // 保存法典主体 LegalCode code = new LegalCode(); code.setCodeName(file.getOriginalFilename()); code.setFileType(StringUtils.getFilenameExtension(file.getOriginalFilename())); codeMapper.insert(code); // 保存章节及关键词 for (ChapterContent chapter : chapters) { CodeChapter entity = new CodeChapter(); entity.setCodeId(code.getId()); entity.setChapterTitle(chapter.getTitle()); entity.setContent(chapter.getContent()); chapterMapper.insert(entity); // 关键词处理 List<String> keywords = keywordService.extractKeywords(chapter.getContent()); for (String kw : keywords) { CodeKeyword keyword = new CodeKeyword(); keyword.setChapterId(entity.getId()); keyword.setKeyword(kw); keyword.setFrequency(Collections.frequency(keywords, kw)); keywordMapper.insert(keyword); } } } } ``` ## 三、接口实现 ```java @RestController @RequestMapping("/api/code") public class CodeImportController { @Autowired private CodeImportService importService; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { try { importService.importCode(file); return ResponseEntity.ok("文件解析入库成功"); } catch (IOException e) { return ResponseEntity.status(500).body("文件处理失败: " + e.getMessage()); } } } ``` ## 四、数据库配置(application.yml) ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/legal_db?useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: map-underscore-to-camel-case: true mapper-locations: classpath*:mapper/**/*.xml ``` **注意事项:** 1. 需要处理大文件上传时配置`spring.servlet.multipart.max-file-size` 2. 建议使用事务管理确保数据一致性[^1] 3. 批量插入建议使用MyBatis-Plus的`saveBatch`方法优化性能 4. PDF解析需要处理特殊格式(如扫描版图片需OCR处理)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值