ITeye博客

Spring Boot 3 示例

samwalt · 2025-10-26 00:03 · java · 编程语言 · Markdown

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>FoodFacility</groupId>
    <artifactId>com.github</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version> <!-- 8.x 版本的旧写法,仍可用 -->
        </dependency>
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-community-dialects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.11.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
            </plugin>
        </plugins>
    </build>
</project>

application.yml


spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
#    driver-class-name: org.sqlite.JDBC
    driver-class-name: com.mysql.cj.jdbc.Driver
#    url: jdbc:sqlite:app.sqlite3
    url: jdbc:mysql://localhost:3306/estate
    username:
    password:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
#        dialect: org.hibernate.community.dialect.SQLiteDialect
        dialect: org.hibernate.dialect.MySQL8Dialect
        format_sql: true

mybatis:
  mapper-locations: classpath*:mapper/*Mapper.xml

logging:
  file: app.log

Application.java


@SpringBootApplication
@MapperScan(basePackages = {"com.github.food_facility.mapper"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

CsvController.java


@RestController
public class CsvController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private CsvService csvService;

    @PostMapping("/upload")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("请选择上传文件");
        }
        if (!file.getOriginalFilename().toLowerCase().endsWith(".csv")) {
            throw new IllegalArgumentException("请上传csv文件");
        }
        List<Estate> list = csvService.process(new BufferedReader(new InputStreamReader(file.getInputStream())));
        return ResponseEntity.ok().body(list);
    }
}

CsvService.java


@Service
public class CsvService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private CsvRepository csvRepository;

    public List<Estate> process(Reader reader) {
        try (CSVReader csvReader = new CSVReaderBuilder(reader).build()) {
            csvReader.readNext();
            String[] line;
            List<Estate> list = new ArrayList<>();
            while ((line = csvReader.readNext()) != null) {
                Estate estate = new Estate();

                estate.setPlatform(line[1]);
                estate.setCommunity(line[2]);
                estate.setSerialNo(line[3]);
                estate.setPrice(Integer.valueOf(line[4]));
                estate.setArea(Float.valueOf(line[5]));
                estate.setUnitPrice(Integer.valueOf(line[6]));
                estate.setComment(line[7]);
                estate = csvRepository.save(estate);
                list.add(estate);
            }

            return list;
        } catch (CsvValidationException e) {
            logger.error("csv格式错误:", e);
        } catch (IOException e) {
            logger.error("处理csv文件错误:", e);
        }
        return List.of();
    }
}

CsvRepository.java


public interface CsvRepository extends JpaRepository<Estate, Long> {
}

GlobalExceptionHandler.java


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ResponseParameter> handleIllegalArgumentException(IllegalArgumentException ex) {
        ResponseParameter rp = new ResponseParameter();
        rp.setCode(HttpStatus.BAD_REQUEST.value());
        rp.setMessage(ex.getMessage());
        return new ResponseEntity<>(rp, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ResponseParameter> handleRuntimeException(RuntimeException ex) {
        ResponseParameter rp = new ResponseParameter();
        rp.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        rp.setMessage(ex.getMessage());
        return new ResponseEntity<>(rp, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Estate.java


@Entity
@Table(name = "estates")
public class Estate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "platform")
    private String platform;
    @Column(name = "community")
    private String community;
    @Column(name = "serial_no")
    private String serialNo;
    @Column(name = "price")
    private Integer price;
    @Column(name = "area")
    private Float area;
    @Column(name = "unit_price")
    private Integer unitPrice;
    @Column(name = "comment")
    private String comment;
}

ResponseParameter.java


public class ResponseParameter<T> {
    private int code;
    private String message;
    private T body;
}


@ExtendWith(SpringExtension.class)
public class CsvServiceTest {
    @Mock
    private CsvRepository csvRepository;

    @InjectMocks
    private CsvService csvService;

    private String csvStrCorrect = """
            id,平台,社区,编号,价格,面积,单价,评论
            1,我爱我家,长桥一村,825544738,330,40.11,82274,"一般装修,户型好,房东爽快"
            """;

    private String csvStrWrong = """
            id,平台,社区,编号,价格,面积,单价,评论
            1;我爱我家,长桥一村,825544738,330,40.11,82274,'一般装修,户型好,房东爽快'
            """;
    @Test
    public void processCorrectCsv() {
        Estate e = new Estate();
        e.setId(1L);
        Mockito.when(csvRepository.save(Mockito.any())).thenReturn(e);

        StringReader reader = new StringReader(csvStrCorrect);
        List<Estate> list = csvService.process(reader);
        Assertions.assertEquals(1, list.size());
        Assertions.assertEquals(1, list.get(0).getId());
    }

    @Test
    public void processWrongCsv() {
        StringReader reader = new StringReader(csvStrWrong);
        Assertions.assertThrows(NumberFormatException.class, () -> csvService.process(reader));
    }
}


<?php

class Data
{
    private string $first_name;
    private string $last_name;
    private int $type;
    private float $height;
    private float $weight;
    private DateTime $birthdate;
    private int $age;

    private static $set = [];

    public function __construct(
        string $first_name,
        string $last_name,
        int $type,
        float $height,
        float $weight,
        DateTime $birthdate,
        int $age,
    ) {
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->type = $type;
        $this->height = $height;
        $this->weight = $weight;
        $this->birthdate = $birthdate;
        $this->age = $age;
    }

    public function getFirst_name(): string
    {
        return $this->first_name;
    }

    public function getLast_name(): string
    {
        return $this->last_name;
    }

    public function getType(): int
    {
        return $this->type;
    }
    public function getHeight(): float
    {
        return $this->height;
    }
    public function getWeight(): float
    {
        return $this->weight;
    }
    public function getBirthdate(): DateTime
    {
        return $this->birthdate;
    }
    public function getAge(): int
    {
        return $this->age;
    }
    public static function validate(string $line): Data
    {
        $columns = explode(",", $line);
        $n = count($columns);
        if ($n !== 6) {
            throw new Exception("The number of columns is not 6.");
        }
        if (ctype_alpha($columns[0])) {
            $first_name = $columns[0];
        } else {
            throw new Exception(
                "First Name contains character which is not letter.",
            );
        }
        if (ctype_alpha($columns[1])) {
            $last_name = $columns[1];
        } else {
            throw new Exception(
                "Last Name contains character which is not letter.",
            );
        }

        $key = "$first_name $last_name";
        if (!isset(self::$set[$key])) {
            self::$set[$key] = true;
        } else {
            throw new Exception("Duplicate First Name - Last Name pair.");
        }

        if (self::validateType($columns[2])) {
            $columns[2] === "TEACHER" ? ($type = 1) : ($type = 2);
        } else {
            throw new Exception("Type is not TEACHER or STUDENT.");
        }

        if (self::validateNumber($columns[3])) {
            $height = $columns[3];
        } else {
            throw new Exception("Height is not number.");
        }

        if (self::validateNumber($columns[4])) {
            $weight = $columns[4];
        } else {
            throw new Exception("Weight is not number.");
        }
        $birthdate = new DateTime($columns[5]);
        $age = (int) date("Y") - (int) $birthdate->format("Y");
        return new Data(
            $first_name,
            $last_name,
            $type,
            $height,
            $weight,
            $birthdate,
            $age,
        );
    }

    public static function validateType(string $type): bool
    {
        if ("TEACHER" === $type || "STUDENT" === $type) {
            return true;
        }
        return false;
    }

    public static function validateNumber(string $num): bool
    {
        if (preg_match('/^\d+(\.\d+)?$/', $num)) {
            return true;
        }
        return false;
    }
}

function save(array $data, int $teacher, int $student): void
{
    $client = new PDO(
        "mysql:host=localhost;dbname=test;charset=utf8mb4",
        "root",
        "",
    );
    try {
        $client->beginTransaction();
        $query =
            "insert into data (first_name,last_name,type,height,weight,birthdate,age) values (:first_name,:last_name,:type,:height,:weight,:birthdate,:age)";
        $stmt = $client->prepare($query);

        foreach ($data as $d) {
            $bind_data = [
                ":first_name" => $d->getFirst_name(),
                ":last_name" => $d->getLast_name(),
                ":type" => $d->getType(),
                ":height" => $d->getHeight(),
                ":weight" => $d->getWeight(),
                ":birthdate" => $d->getBirthdate()->format("Y-m-d"),
                ":age" => $d->getAge(),
            ];
            $stmt->execute($bind_data);
        }

        $query = "insert into summary (type, num) values (:type, :num)";
        $stmt = $client->prepare($query);
        $stmt->execute([":type" => "TEACHER", ":num" => $teacher]);
        $stmt->execute([":type" => "STUDENT", ":num" => $student]);

        $client->commit();
    } catch (PDOException $e) {
        if (isset($client) && $client->inTransaction()) {
            $client->rollBack();
        }
    }
}

$reader = fopen("data.csv", "r");
$writer = fopen("error.txt", "w");
$line = fgets($reader);
$list = [];
$teacher = 0;
$student = 0;
while (($line = fgets($reader)) != false) {
    try {
        $data = Data::validate($line);
        $list[] = $data;
        if ($data->getType() === 1) {
            $teacher += 1;
        } else {
            $student += 1;
        }
    } catch (Exception $e) {
        fwrite($writer, $line);
    }
}
save($list, $teacher, $student);
fclose($reader);
fclose($writer);


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。