java 从实体,mapper,xml,service,iml,controller怎么批量插入[{ "id": 1,"bill_list": [ {"name": "附件1"}]}]该数据
时间: 2024-12-10 18:18:53 浏览: 9
要在Java中实现批量插入数据,你需要按照以下步骤进行操作:实体类、Mapper接口、XML映射文件、Service层和Controller层。以下是一个完整的示例:
### 1. 实体类
```java
// MainEntity.java
public class MainEntity {
private Integer id;
private List<Bill> billList;
// Getters and Setters
}
// Bill.java
public class Bill {
private String name;
// Getters and Setters
}
```
### 2. Mapper接口
```java
// MainMapper.java
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface MainMapper {
void batchInsert(@Param("entities") List<MainEntity> entities);
}
```
### 3. XML映射文件
```xml
<!-- MainMapper.xml -->
<mapper namespace="com.example.mapper.MainMapper">
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO main_table (id) VALUES
<foreach collection="entities" item="entity" separator=",">
(#{entity.id})
</foreach>
</insert>
<insert id="batchInsertBill" parameterType="java.util.List">
INSERT INTO bill_table (main_id, name) VALUES
<foreach collection="entities" item="entity" index="index" separator=",">
<foreach collection="entity.billList" item="bill" separator=",">
(#{entity.id}, #{bill.name})
</foreach>
</foreach>
</insert>
</mapper>
```
### 4. Service层
```java
// MainService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MainService {
@Autowired
private MainMapper mainMapper;
public void batchInsert(List<MainEntity> entities) {
mainMapper.batchInsert(entities);
mainMapper.batchInsertBill(entities);
}
}
```
### 5. Controller层
```java
// MainController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/main")
public class MainController {
@Autowired
private MainService mainService;
@PostMapping("/batchInsert")
public String batchInsert(@RequestBody List<MainEntity> entities) {
mainService.batchInsert(entities);
return "Success";
}
}
```
### 6. 数据库表
假设你有两张表:`main_table` 和 `bill_table`。
```sql
CREATE TABLE main_table (
id INT PRIMARY KEY
);
CREATE TABLE bill_table (
id INT AUTO_INCREMENT PRIMARY KEY,
main_id INT,
name VARCHAR(255),
FOREIGN KEY (main_id) REFERENCES main_table(id)
);
```
### 7. 数据示例
```json
[
{
"id": 1,
"bill_list": [
{"name": "附件1"}
]
}
]
```
通过以上步骤,你可以在Java中实现批量插入数据的功能。
阅读全文