sharp-excel使用指北:高级部分(二)

简介

sharp-excel 是一个操作Excel、Word工具的java实现。依赖apache的 POI。目前只开发了Excel的部分,Word部分还没有实现。
pom.xml

<dependency>
    <groupId>com.rick.office</groupId>
    <artifactId>sharp-excel</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>

设计的理念是定(x, y)坐标,然后写数据

方法测试

在指定的坐标位置,写入数据

单元格数据

@Test
public void testCell() throws IOException {
    File file = new File("/Users/rick/Documents/3.xlsx");

    ExcelWriter excelWriter = new ExcelWriter();

    excelWriter.writeCell(new ExcelCell(4, 5, "hello"));

    excelWriter.toFile(new FileOutputStream(file));
}

在坐标(4, 5)的单元格写入「hello」
http://xhope.top/wp-content/uploads/2021/09/0.png

行数据

@Test
public void writeRow() throws IOException {
    File file = new File("/Users/rick/Documents/9.xlsx");
    ExcelWriter excelWriter = new ExcelWriter();
    excelWriter.writeRow(new ExcelRow(2,2, new Object[] {1, 2, 3, 4, 5, "hello", true}));
    excelWriter.toFile(new FileOutputStream(file));
}

从坐标是(2, 2) 的位置开始,写入「一行」数据:1, 2, 3, 4, 5, “hello”, true
http://xhope.top/wp-content/uploads/2021/09/2.png

列数据

@Test
public void writeColumn() throws IOException {
    File file = new File("/Users/rick/Documents/8.xlsx");
    ExcelWriter excelWriter = new ExcelWriter();
    excelWriter.writeColumn(new ExcelColumn(2,2, new Object[] {1, 2, 3, 4, 5, "hello", true}));
    excelWriter.toFile(new FileOutputStream(file));
}

从坐标是(2, 2) 的位置开始,写入「一列」数据:1, 2, 3, 4, 5, “hello”, true
http://xhope.top/wp-content/uploads/2021/09/1.png

合并单元格

@Test
public void testWriteMerge() throws IOException {
    File file = new File("/Users/rick/Documents/0.xlsx");

    ExcelWriter excelWriter = new ExcelWriter();

    ExcelCell cell = new ExcelCell(2, 3, "hello");

    cell.setRowSpan(3);
    cell.setColSpan(2);

    excelWriter.writeCell(cell);

    excelWriter.toFile(new FileOutputStream(file));
}

在坐标(2, 3)的单元格写入「hello」,占3行2列
http://xhope.top/wp-content/uploads/2021/09/merge.png

设置样式

单元格

@Test
public void testWriteCellWithStyle() throws IOException {
    File file = new File("/Users/rick/Documents/3.xlsx");

    ExcelWriter excelWriter = new ExcelWriter();

    ExcelCell cell = new ExcelCell(2,1, "hello");

    cell.setHeightInPoints(50f);
    cell.setStyle(createStyle(excelWriter.getBook()));

    excelWriter.writeCell(cell);

    excelWriter.toFile(new FileOutputStream(file));
}

http://xhope.top/wp-content/uploads/2021/09/s1.png

@Test
public void testWriteRowWithStyle() throws IOException {
    File file = new File("/Users/rick/Documents/3.xlsx");

    ExcelWriter excelWriter = new ExcelWriter();

    excelWriter.getActiveSheet().setColumnWidth(2, 5600);

    ExcelRow row = new ExcelRow(2,2, new Object[] {1.2d, 23, "3", true, LocalDate.now()});
    row.setStyle(createStyle(excelWriter.getBook()));
    excelWriter.writeRow(row);

    excelWriter.toFile(new FileOutputStream(file));
}

http://xhope.top/wp-content/uploads/2021/09/s2.png

同行设置

复杂例子

@Test
public void testComplex() throws IOException {
    File file = new File("/Users/rick/Documents/7.xlsx");
    ExcelWriter excelWriter = new ExcelWriter();

    ExcelCell cell1 = new ExcelCell(1,1, "国内仓");
    cell1.setColSpan(3);
    cell1.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell2 = new ExcelCell(4,1, "香港仓");
    cell2.setRowSpan(2);
    cell2.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell3 = new ExcelCell(5,1, "香港直运仓");
    cell3.setRowSpan(2);
    cell3.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell4 = new ExcelCell(6,1, "供应链未完成数量");
    cell4.setRowSpan(2);
    cell4.setStyle(createStyle(excelWriter.getBook()));

    ExcelRow row1 = new ExcelRow(1, 2, new Object[] {"苏州成品仓", "苏州样品仓", "深圳成品仓"});
    row1.setStyle(createStyle(excelWriter.getBook()));

    ExcelRow row2 = new ExcelRow(1, 3, new Object[] {"50", "0", "1"});
    row2.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell5 = new ExcelCell(1,4, "国内仓锁货数量");
    cell5.setColSpan(3);
    cell5.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell6 = new ExcelCell(1,5, "9");
    cell6.setColSpan(3);
    cell6.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell7 = new ExcelCell(4,3, "29");
    cell7.setRowSpan(3);
    cell7.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell8 = new ExcelCell(5,3, "39");
    cell8.setRowSpan(3);
    cell8.setStyle(createStyle(excelWriter.getBook()));

    ExcelCell cell9 = new ExcelCell(6,3, 88);
    cell9.setRowSpan(3);
    cell9.setStyle(createStyle(excelWriter.getBook()));

    ExcelColumn column = new ExcelColumn(7, 1, new Object[] {"新增", "2", "23", 23, 34.2f});
    column.setStyle(createStyle(excelWriter.getBook()));

    excelWriter.writeCell(cell1);
    excelWriter.writeCell(cell2);
    excelWriter.writeCell(cell3);
    excelWriter.writeCell(cell4);
    excelWriter.writeCell(cell5);
    excelWriter.writeCell(cell6);
    excelWriter.writeCell(cell7);
    excelWriter.writeCell(cell8);
    excelWriter.writeCell(cell9);
    excelWriter.writeRow(row1);
    excelWriter.writeRow(row2);
    excelWriter.writeColumn(column);

    excelWriter.getActiveSheet().setColumnWidth(0, 5600);
    excelWriter.getActiveSheet().setColumnWidth(1, 5600);
    excelWriter.getActiveSheet().setColumnWidth(2, 5600);
    excelWriter.getActiveSheet().setColumnWidth(3, 5600);
    excelWriter.getActiveSheet().setColumnWidth(4, 5600);
    excelWriter.getActiveSheet().setColumnWidth(5, 5600);
    excelWriter.getActiveSheet().setColumnWidth(6, 5600);

    excelWriter.toFile(new FileOutputStream(file));

}

private XSSFCellStyle createStyle(XSSFWorkbook book) {

    XSSFCellStyle cellStyle = book.createCellStyle();
    // 定义颜色
    XSSFColor color = new XSSFColor(Color.black, new DefaultIndexedColorMap());

    // 设置边框(合并这个不生效) 需要单独在CellRangeAddress设置
    cellStyle.setBorderLeft(BorderStyle.THIN);
    cellStyle.setBorderRight(BorderStyle.THIN);
    cellStyle.setBorderTop(BorderStyle.THIN);
    cellStyle.setBorderBottom(BorderStyle.THIN);

    cellStyle.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color);
    cellStyle.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color);
    cellStyle.setBorderColor(XSSFCellBorder.BorderSide.TOP, color);
    cellStyle.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color);

    // 水平居中
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    // 垂直居中
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

    return cellStyle;
}

http://xhope.top/wp-content/uploads/2021/09/complex.png

POI原生实现例子

@Test
public void testNative() throws IOException {
    File file = new File("/Users/rick/Documents/2.xlsx");

    XSSFWorkbook book = new XSSFWorkbook();
    XSSFSheet sheet = book.createSheet("sheet-rick");

    // 设置第一列的框
    sheet.setColumnWidth(0, 3766);

    XSSFRow row = sheet.createRow(0);


    // 设置高度
    row.setHeightInPoints(24);
//        row.setRowStyle();
    XSSFCell cell = row.createCell(1);
    cell.setCellValue("hello");
//        cell.setCellStyle();


    XSSFCellStyle cellStyle = book.createCellStyle();

    // 定义颜色
    XSSFColor color = new XSSFColor(java.awt.Color.BLUE, new DefaultIndexedColorMap());
    XSSFColor color2 = new XSSFColor(Color.RED, new DefaultIndexedColorMap());
    XSSFColor color3 = new XSSFColor(Color.GREEN, new DefaultIndexedColorMap());

    // 填充色
    cellStyle.setFillForegroundColor(color2);
    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    // 文字色
    XSSFFont font = book.createFont();
    font.setColor(color);
    cellStyle.setFont(font);

    // 设置边框(合并这个不生效) 需要单独在CellRangeAddress设置
//        cellStyle.setBorderBottom(BorderStyle.MEDIUM);
//        cellStyle.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color3);

    // 水平居中
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    // 垂直居中
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

    // 设置样式
    cell.setCellStyle(cellStyle);

    // 合并单元格
    CellRangeAddress region = new CellRangeAddress(0, 1, 1, 2);
    sheet.addMergedRegion(region);

    //
    System.out.println(cellStyle.getBorderBottom() == BorderStyle.NONE);
    setRegionStyle(sheet, region);

    book.write(new FileOutputStream(file));
    book.close();

}

/**
 * 设置边框
 //  * @param region
 */
 private void setRegionStyle(XSSFSheet sheet, CellRangeAddress region) {
    //全部完成之后
    XSSFRow xrow = (XSSFRow) CellUtil.getRow(region.getFirstRow(), sheet);
    XSSFCell xccell = (XSSFCell) CellUtil.getCell(xrow, region.getFirstColumn());

    XSSFCellStyle style = xccell.getCellStyle();

    for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
        XSSFRow row = (XSSFRow) CellUtil.getRow(i, sheet);
        for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
            XSSFCell cell = (XSSFCell) CellUtil.getCell(row, j);
            cell.setCellStyle(style);
            System.out.println("-----");
        }
    }
 }

sharp-excel使用指北:基础使用(一)

简介

sharp-excel 是一个操作Excel、Word工具的java实现。依赖apache的 POI。目前只开发了Excel的部分,Word部分还没有实现。
pom.xml

<dependency>
    <groupId>com.rick.office</groupId>
    <artifactId>sharp-excel</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>

方法测试

Excel读取

@Test
public void testRead() throws Exception {
    File file = new File("/Users/rick/Documents/1.xlsx");

    ExcelReader.readExcelContent(new FileInputStream(file), (index, data, sheetIndex, sheetName) -> {
        System.out.print("index: " + index + ", ");
        for (Object d : data) {
            System.out.print(d + ", ");
        }
        System.out.println();

        return true;
    });
}

控制台输出

index: 0, 姓名, 年龄,
index: 1, rick, 23.0,
index: 2, jim, 88.0,

Excel写入

基本使用:分别构建

分别构建「表头」和「数据」,两者没有关联

@Test
public void testBase() throws IOException {
    File file = new File("/Users/rick/Documents/11.xlsx");
    TableColumn column1 = new TableColumn("姓名");
    TableColumn column2 = new TableColumn("年龄");

    List<TableColumn> columnList = Lists.newArrayList(column1, column2);
    List<Object[]> rows = Lists.newArrayList(new Object[]{"rick", 23}, new Object[] {"jim", 88});
    GeneralExportTable excelTable =  new GeneralExportTable(columnList, rows);

    excelTable.write(new FileOutputStream(file));
}

基本使用:Map构建数据

分别构建「表头」和「数据」,两者通过key关联

@Test
public void testBaseMap() throws IOException {
    File file = new File("/Users/rick/Documents/2.xlsx");

    MapTableColumn column1 = new MapTableColumn("name", "姓名");
    MapTableColumn column2 = new MapTableColumn("age", "年龄");
    List<MapTableColumn> columnList = Lists.newArrayList(column1, column2);

    Map<String, Object> map1 = Maps.newHashMapWithExpectedSize(2);
    map1.put("name", "rick");
    map1.put("age", 12);

    Map<String, Object> map2 = Maps.newHashMapWithExpectedSize(2);
    map2.put("name", "jim");
    map2.put("age", 88);

    List<Map<String, Object>> rows = Lists.newArrayList(map1, map2);
    MapExcelTable excelTable =  new MapExcelTable(columnList, rows);

    excelTable.write(new FileOutputStream(file));
    }

基本使用+设置数据单元格样式

构建表头和数据

@Test
public void testBaseWithStyle() throws IOException {
    File file = new File("/Users/rick/Documents/22.xlsx");

    TableColumn column1 = new TableColumn("姓名");
    TableColumn column2 = new TableColumn("年龄");

    List<TableColumn> columnList = Lists.newArrayList(column1, column2);
    List<Object[]> rows = Lists.newArrayList(new Object[]{"rick", 23}, new Object[] {"jim", 88});

    GeneralExportTable excelTable =  new GeneralExportTable(columnList, rows);

    XSSFCellStyle cellStyle = excelTable.getExcelWriter().getBook().createCellStyle();
    // 填充色
    XSSFColor color = new XSSFColor(Color.GREEN, new DefaultIndexedColorMap());
    cellStyle.setFillForegroundColor(color);
    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    // 数据部分样式
    excelTable.setRowStyle(cellStyle);

    // 表头部分样式
//         excelTable.setColumnStyle(cellStyle);

    excelTable.write(new FileOutputStream(file));
}

http://xhope.top/wp-content/uploads/2021/09/ss.png

  • setColumnStyle 表头部分样式
  • setRowStyle 数据部分样式

HTML中table解析导出

解析table标签,然后导出

@Test
public void testHtmlExport() throws IOException {
    HtmlExcelTable excelTable = new HtmlExcelTable();

    excelTable.getExcelWriter().getActiveSheet().setColumnWidth(0, 8000);

    excelTable.write("<table class=\"table table-responsive-sm table-bordered table-sm table-stock\">\n" +
            "                <tbody>\n" +
            "                    <tr>\n" +
            "                        <th colspan=\"4\">国内仓</th>\n" +
            "                        <th rowspan=\"2\">香港仓</th>\n" +
            "                        <th rowspan=\"2\">香港直运仓</th>\n" +
            "                        <th rowspan=\"2\">供应链未完成数量</th>\n" +
            "                    </tr>\n" +
            "                    <tr>\n" +
            "                        <th>深圳成品仓</th>\n" +
            "                        <th>苏州成品仓</th>\n" +
            "                        <th>深圳待处理仓</th>\n" +
            "                        <th>苏州样品仓</th>\n" +
            "                    </tr>\n" +
            "                    <tr>\n" +
            "                        <td>13,558</td>\n" +
            "                        <td>0</td>\n" +
            "                        <td>18</td>\n" +
            "                        <td>0</td>\n" +
            "                        <td rowspan=\"3\">0</td>\n" +
            "                        <td rowspan=\"3\">0</td>\n" +
            "                        <td rowspan=\"3\">\n" +
            "                            <a href=\"javascript:;\" id=\"otherDetailBtn\">1,000,500</a>\n" +
            "                            \n" +
            "                        </td>\n" +
            "                    </tr>\n" +
            "                    <tr>\n" +
            "                        <th colspan=\"4\">国内仓锁货数量</th>\n" +
            "                    </tr>\n" +
            "                    <tr>\n" +
            "                        <td colspan=\"4\">\n" +
            "                            <a href=\"javascript:;\" id=\"reserveDetailBtn\">12,000</a>\n" +
            "                            \n" +
            "                        </td>\n" +
            "                    </tr>\n" +
            "                </tbody>\n" +
            "            </table>", new FileOutputStream(new File("/Users/rick/Documents/a.xlsx")));
}

http://xhope.top/wp-content/uploads/2021/09/htm.png

集成GridService导出

在Spring上下文中,通过 ExportUtils,集成 GridService 获取数据源,导出Excel。
提供了方便的导出操作。只需要根据查询SQL,直接导出excel文件。

pom.xml 添加依赖

<dependency>
    <groupId>com.rick.db</groupId>
    <artifactId>sharp-excel</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
public static final void export(String sql, Map<String, ?> params, OutputStream outputStream, List<MapTableColumn> columnList)

测试代码

/**
 * 查询sql导出
 */
@Test
public void testSqlExport() throws IOException {
    Map params = new HashMap<>();
    // 业务参数
    params.put("title", "version");

    ExportUtils.export("SELECT id, title FROM t_demo WHERE title like :title", params,
            new FileOutputStream("/Users/rick/Downloads/export/t_demo.xlsx"),
            Lists.newArrayList(
                    new MapTableColumn("title", "标题") // 导出文件中第一列为标题,且仅导出标题,忽略id
//                        new MapTableColumn("id", "ID")
            ));
}

sharp-database使用指北

简介

sharp-database 是一个持久化操作工具的java实现,主要做查询功能。底层依赖 JdbcTemplate 。可以结合 MyBatis 的动态SQL一起使用。sharp-database 作为数据库操作工具的补充,不是用来了替换 MyBatisJPA。目前支持 MysqlOracle 两种数据库,默认支持 Mysql

pom.xml 添加依赖

<dependency>
    <groupId>com.rick.db</groupId>
    <artifactId>sharp-database</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

application.xml

sharp:
  database:
    type: oracle

方法测试

SharpService

获取Map集合

List<Map<String, Object>> query(String sql, Map<String, ?> params)

测试代码

@Test
public void testListAsMap() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
//        params.put("id", "1341369230607347714,1341299740150394882,1341734037772668930,1341313565406904322,1341368363682439169");
//        params.put("id", Arrays.asList(1341369230607347714L,
//                1341299740150394882L,1341734037772668930L,1341313565406904322L,1341368363682439169L));
//        params.put("id", Sets.newHashSet(1341369230607347714L,
//                1341299740150394882L, 1341734037772668930L, 1341313565406904322L, 1341368363682439169L));
    params.put("id", new Long[] { 1341369230607347714L,
            1341299740150394882L, 1341734037772668930L, 1341313565406904322L, 1341368363682439169L});

    params.put("title", "haha");
    params.put("createTime", "2020-10-22 17:27:41");
    params.put("createBy", "156629745675451");

    List<Map<String, Object>> list = gridService.query(sql, params);
    list.forEach(System.out::println);
}

SQL打印

SELECT id, title, description, create_time, is_delete
FROM t_project
WHERE id IN (:id0, :id1, :id2, :id3, :id4)
  AND UPPER(title) LIKE CONCAT('%', UPPER(:title), '%') ESCAPE '\\'
    AND create_time > :createTime

args:=> [{id0=1341734037772668930, createTime=2020-10-22 17:27:41, id2=1341313565406904322, id1=1341368363682439169, id4=1341369230607347714, id3=1341299740150394882, title=haha, create_by=156629745675451}]    

代码中SQL有5个变量:id、title、createTime、deleted、create_by。但是params中只提供了id、title、createTime、create_by4个参数。在执行查询的时候会忽略没有提供参数的变量。类似于 Mybatis 中的动态SQL。只是这里不需要通过if去手动判断。
常见的变量形式:

  • id = :id
  • id in (:id) 值可以是List Set 等实现了 Iterable接口的对象;可以是数组,如new Long[] {1, 2};或者是以逗号分割的字符串,如“1341369230607347714,1341299740150394882”
  • title like :title 不区分大小写,%:title%
  • create_time > :createTime
  • id = ${id} 这个是替换操作,会有sql注入的风险

获取对象集合

public <T> List<T> query(String sql, Map<String, ?> params, Class<T> clazz)

测试代码

@Test
public void testListAsClass() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("id", new Long[] { 1341369230607347714L,1341299740150394882L});

    List<Project> list = gridService.query(sql, params, Project.class);
    list.forEach(System.out::println);
}

获取自定义的集合

public <T> List<T> query(String sql, Map<String, ?> params, JdbcTemplateCallback<T> jdbcTemplateCallback)

测试代码

@Test
public void testListAsCustom() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("title", "title");

    List<String> list = gridService.query(sql, params, new SharpService.JdbcTemplateCallback<String>() {
        @Override
        public List<String> query(NamedParameterJdbcTemplate jdbcTemplate, String sql, Map<String, ?> paramMap) {
            return jdbcTemplate.query(sql, paramMap, new RowMapper<String>() {
                public String mapRow(ResultSet rs, int var2) throws SQLException {
                    return rs.getString(1) + "-"  + rs.getString(2);
                }
            });
        }
    });
    list.forEach(System.out::println);
}

输出的结果是一个String集合,String是id和title通过“-”连接起来的。打印结果如下:

1341734037772668930-title1
1341736555407835137-title2

查询两列,第一列key,第二列value

public <T> List<T> query(String sql, Map<String, ?> params, JdbcTemplateCallback<T> jdbcTemplateCallback)

测试代码

@Test
public void testKeyValue() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("id", new Long[] { 1341369230607347714L,1341299740150394882L});

    Map<Object, Object> map = gridService.queryForKeyValue(sql, params);
    System.out.println(map);
}

打印结果如下:

{1341299740150394882=this is project title, 1341369230607347714=hello world}

查询单个对象Map,用Optional包装

public Optional<Map<String, Object>> queryForObject(String sql, Map<String, ?> params)

测试代码

@Test
public void testQueryObject() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("id", new Long[] { 1341369230607347714L});

    Optional<Map<String, Object>> optionalMap = gridService.queryForObject(sql, params);
    System.out.println(optionalMap.isPresent());
    if (optionalMap.isPresent()) {
        System.out.println(optionalMap.get());
    }
}

打印结果如下:

{id=1341369230607347714, title=hello world, description=hello你税的朋友, create_time=2020-12-22 21:05:21.0, is_delete=false, create_by=156629745675451}

NOTE: 如果查询结果超过1条记录,抛出异常。

查询单个Bean对象,用Optional包装

public Optional<Map<String, Object>> queryForObject(String sql, Map<String, ?> params)

测试代码

@Test
public void testQueryBean() {
    // language=SQL
    String sql = "SELECT id, title, description, create_time, is_delete, create_by\n" +
            "FROM t_project\n" +
            "WHERE id IN (:id)\n" +
            "  AND title LIKE :title\n" +
            "  AND create_time > :createTime\n" +
            "  AND is_delete = :deleted" +
            "  AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("id", new Long[] { 1341369230607347714L});

    Optional<Project> optionalMap = gridService.queryForObject(sql, params, Project.class);
    System.out.println(optionalMap.isPresent());
    if (optionalMap.isPresent()) {
        System.out.println(optionalMap.get());
    }
}

打印结果如下:

Project(id=1341369230607347714, title=hello world, description=hello你税的朋友, coverUrl=null, ownerId=null, deleted=null, createdAt=null, createdBy=null, updatedAt=null, updatedBy=null)

重载方法,添加了一个class参数。

NOTE: 如果查询结果超过1条记录,抛出异常。

更新操作

public int update(String sql, Map<String, ?> params)

测试代码

@Test
@Transactional(rollbackFor = Exception.class)
public void testUpdate() {
    // language=SQL
    String sql = "UPDATE t_project SET title = :title, description = :description, is_delete = :deleted\n" +
            "WHERE id IN (:id)\n" +
            "  AND create_time > :createTime\n" +
            "AND create_by = ${createBy}";

    Map<String, Object> params = new HashMap<>();
    params.put("id", new Long[] { 1341369230607347714L, 2L});
    params.put("createTime", "2019-10-22 17:27:41");


//        params.put("title", "new title xx");
    params.put("description", "new description3");
    params.put("deleted", true);

    int count = gridService.update(sql, params);
    System.out.println(count);
}

MappedSharpService

结合 Mybatis 动态SQL的特点,将SQL写在xml文件中。
pom.xml 添加依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
    <scope>provided</scope>
</dependency>

获取自定义的集合

public <T> T handle(String selectId, Map<String, Object> params, SharpServiceHandler<T> sharpServiceHandler)
public <T> T handle(SharpService sharpService, String sql, Map<String, Object> params)

测试代码

@Autowired
private MappedSharpService mappedSharpService;

@Test
public void testMappedSharpService() {
    // findById标签必须是<select,不能是<sql>
    Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
    params.put("title", "");
    params.put("id", 5);

    Optional<Project> optionalProject = mappedSharpService.handle("com.yodean.component.project.modules.project.dao.mapper.ProjectMapper.findById",
            params,
            (sharpService, sql, params1) -> sharpService.queryForObject(sql, params1, Project.class)
    );

    List<Project> projectList = mappedSharpService.handle("com.yodean.component.project.modules.project.dao.mapper.ProjectMapper.findById",
            params,
            (sharpService, sql, params1) -> sharpService.query(sql, params1, Project.class)
    );

    List<Map<String, Object>> projectMapList = mappedSharpService.handle("com.yodean.component.project.modules.project.dao.mapper.ProjectMapper.findById",
            params,
            (sharpService, sql, params1) -> sharpService.query(sql, params1)
    );

    log.info("project is {}", optionalProject.orElse(null));
    log.info("project list as object is {}", projectList);
    log.info("project list as as Map is {}", projectMapList);

}

mapper.xml

<mapper namespace="com.yodean.component.project.modules.project.dao.mapper.ProjectMapper">
    <select id="findById">
         <!-- gridService不能用这种变量形式 id = #{id} 或 id = ?,只能用id = :id -->
        select
        <include refid="column" />
        from t_project where
                id=:id
        <if test="title != null and title !=''">
            and title like ${title}
        </if>
        <if test="description != null and description !=''">
            and description like :description
        </if>
    </select>

    <sql id="column">
        id, title, description, 'haha' as plain
    </sql>
</mapper>

真正执行查询操作的还是 SharpService,只是利用了 Mybatis 动态获取了SQL。
xml中SQL写法有两点需要注意:

  • 标签必须是 select,不能是sql
  • gridService不能用这种变量形式 id = #{id} 或 id = ?,只能用id = :id

GridService/GridUtils

GridService 继承自 SharpService,增加了分页相关的操作。GridUtils 又依赖了 GridService 提供了更方便的操作。所以我们分页操作只需要使用 GridUtils就可以了。

统计结果是数字的单行记录

public static final List<BigDecimal> numericObject(String sql, Map<String, ?> params)

比如:

  • 合计summary: select sum(score), sum(money) from t_xx
  • 平均值avg: select avg(score), avg(money) from t_xx

测试代码

/**
 * 列求和
 */
@Test
public void testSummary() {
    List<BigDecimal> list = GridUtils.numericObject("SELECT SUM(work_time) FROM t_demo", null);
    list.forEach(System.out::println);
}

注意:

  • 记录数只能是一行
  • 数字列,可以列可以映射成 BigDecimal

查询table结果集

public static final Grid<Map<String, Object>> list(String sql, Map<String, ?> params, String countSQL, String... sortableColumns)

比如:

  • countSQL:可以单独指定count的SQL,可以为null
  • sortableColumns:可以允许排序的列,查询字段必须包含id列,不然mysql排序会有问题

测试代码

@Test
public void testList() {
    Map params = new HashMap<>();
    // 通用参数
    params.put("page", 1);
    params.put("size", 2);
    params.put("sidx", "title");
    params.put("sord", "desc");

    // 业务参数
    params.put("title", "version");

//        Grid list = GridUtils.list("SELECT id, title FROM t_demo WHERE title like :title", params, null, new String[]{"title"});
    Grid list = GridUtils.list("SELECT id, title FROM t_demo WHERE title like :title", params, null, "title");
    list.getRows().forEach(System.out::println);
}

SQL打印

    SELECT *
    FROM (SELECT id, title FROM t_demo WHERE UPPER(title) LIKE CONCAT('%', UPPER(:title), '%') ESCAPE '\\') temp_
    ORDER BY temp_.title DESC, temp_.id DESC
    LIMIT 0,2

结果集 Grid 数据结构

public class Grid<T> implements Serializable {

    /**
     * 当前页面索引
     */
    private int page;

    /**
     * 一页显示记录条数
     */
    private int pageSize;

    /***
     * 总纪录数
     */
    private long records;

    /***
     * 总页数
     */
    private long totalPages;

    /***
     * 数据项
     */
    private List<T> rows;

    public static <T> Grid<T> emptyInstance(int pageSize) {
        Grid<T> grid = Grid.builder().totalPages(0)
                .page(1)
                .rows(Collections.EMPTY_LIST)
                .pageSize(pageSize)
                .records(0)
                .build();
        return grid;
    }
}

SQLUtils处理一些SQL层面的操作

查询根据多个id删除记录

public static int deleteByIn(String tableName, String deleteColumn, Collection<?> deleteValues)

测试代码

@Test
public void testDeleteByIn() {
    int deletedCount = SQLUtils.deleteByIn("t_demo", "id", Arrays.asList(1358619329104297985L, 1358619736027283457L));
    System.out.println(deletedCount);
}

查询根据多个id删除记录

public static int deleteByNotIn(String tableName, String deleteColumn, Collection<?> deleteValues)

测试代码和上面类似,略。

查询根据参数个数,生成in的参数?

public static String formatInSQLPlaceHolder(int paramSize)

if paramSize = 4 format as (?, ?, ?, ?)

导出Excel

pom.xml 添加依赖

<dependency>
    <groupId>com.rick.office</groupId>
    <artifactId>sharp-excel</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>

ExportUtils 依赖了 GridService 提供了方便的导出操作。只需要根据查询SQL,直接导出excel文件。

public static final void export(String sql, Map<String, ?> params, OutputStream outputStream, List<MapTableColumn> columnList)

测试代码

/**
 * 查询sql导出
 */
@Test
public void testSqlExport() throws IOException {
    Map params = new HashMap<>();
    // 业务参数
    params.put("title", "version");

    ExportUtils.export("SELECT id, title FROM t_demo WHERE title like :title", params,
            new FileOutputStream("/Users/rick/Downloads/export/t_demo.xlsx"),
            Lists.newArrayList(
                    new MapTableColumn("title", "标题") // 导出文件中第一列为标题,且仅导出标题,忽略id
//                        new MapTableColumn("id", "ID")
            ));
}

Controller

编写一个通用的Controller,统一获取Table结果集 Grid ,需要结合之前介绍用到的 MappedSharpServiceGridUtils

QueryController.java

@RestController
@RequestMapping("query")
@RequiredArgsConstructor
public class QueryController {

    private final CommonTableGridBySelectIdService selectIdService;

    private static final Map<String, String> selectIdMap = new HashMap<>();

    static {
        // 在此注册selectId
        selectIdMap.put("product-list", "com.yodean.component.project.modules.project.dao.mapper.ProjectMapper.findById");
    }

    @GetMapping("{selectKey}")
    public Grid request(@PathVariable String selectKey, HttpServletRequest request) {
        return selectIdService.list(selectIdMap.get(selectKey), request);
    }
}

mapper.xml中的查询SQL,之前已经贴过了。

CommonTableGridBySelectIdService.java

@Service
@RequiredArgsConstructor
public class CommonTableGridBySelectIdService {

    private final MappedSharpService mappedSharpService;

    public Grid<Map<String, Object>> list(String selectId, HttpServletRequest request) {
        Assert.notNull(selectId, "selectId cannot be null");
        Map requestParams = HttpServletRequestUtils.getParameterMap(request);
        Object sidx = requestParams.get(PageModel.PARAM_SIDX);

        return  mappedSharpService.handle(selectId, requestParams,
                (SharpServiceHandler<Grid<Map<String, Object>>>) (gridService, sql, params) -> GridUtils.list(sql, params, null
                        , Objects.isNull(sidx) ? null : sidx.toString()));
    }
}

测试:

GET /query/product-list?title='hello world'&amp; description=hello&amp; sidx=title HTTP/1.1
Host: localhost:8912
cache-control: no-cache
Postman-Token: c3707206-0c4f-492e-aee2-586ac3750411

结果集JSON

{
    "success": true,
    "code": 200,
    "msg": "成功",
    "data": {
        "page": 1,
        "pageSize": 15,
        "records": 1,
        "totalPages": 1,
        "rows": [
            {
                "id": 1341368363682439169,
                "title": "hello world",
                "description": "hello",
                "plain": "haha"
            }
        ]
    }
}

应用架构(MVC + 分层架构 + 领域驱动COLA)

应用架构

使用阿里云的应用生成器:https://start.aliyun.com/bootstrap.html 生成应用架构

MVC

MVC模式(Model–view–controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。

MVC模式最早由Trygve Reenskaug在1978年提出[1],是施乐帕罗奥多研究中心(Xerox PARC)在20世纪80年代为程序语言Smalltalk发明的一种软件架构。MVC模式的目的是实现一种动态的程序设计,使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。除此之外,此模式透过对复杂度的简化,使程序结构更加直观。软件系统透过对自身基本部分分离的同时也赋予了各个基本部分应有的功能。专业人员可以依据自身的专长分组:

  • 模型(Model) – 程序员编写程序应有的功能(实现算法等等)、数据库专家进行数据管理和数据库设计(可以实现具体的功能)。
  • 视图(View) – 界面设计人员进行图形界面设计。
  • 控制器(Controller)- 负责转发请求,对请求进行处理。
    https://zh.wikipedia.org/wiki/MVC

架构项目依赖

http://xhope.top/wp-content/uploads/2021/09/a1.png

架构代码分析

├── pom.xml
├── project-model
│   ├── pom.xml
│   └── src
│       └── main
│           ├── java
│           │   └── com
│           │       └── yodean
│           │           └── project
│           │               ├── demos
│           │               │   └── web
│           │               │       └── User.java
│           │               └── mybatis
│           │                   ├── config
│           │                   │   ├── MVCMybatisDemoConfig.java
│           │                   │   └── MybatisDemoConfig.java
│           │                   ├── entity
│           │                   │   ├── MVCMybatisDemoUser.java
│           │                   │   └── MybatisDemoUser.java
│           │                   └── mapper
│           │                       ├── MVCMybatisDemoUserMapper.java
│           │                       └── MybatisDemoUserMapper.java
│           └── resources
│               ├── data.sql
│               ├── mappers
│               │   ├── MybatisDemoUserMapper.xml
│               │   └── mybatisdemouser-mapper.xml
│               └── schema.sql
├── project-service
│   ├── pom.xml
│   └── src
│       └── main
│           └── java
│               └── com
│                   └── yodean
│                       └── project
│                           ├── GetUserInfoService.java
│                           └── impl
│                               └── GetUserInfoServiceImpl.java
├── project-web
│   ├── pom.xml
│   └── src
│       └── main
│           ├── java
│           │   └── com
│           │       └── yodean
│           │           └── project
│           │               ├── controller
│           │               │   └── GreetingController.java
│           │               ├── demos
│           │               │   ├── GreetingThymeleafController.java
│           │               │   └── web
│           │               │       ├── BasicController.java
│           │               │       └── PathVariableController.java
│           │               └── mybatis
│           │                   └── controller
│           │                       └── MybatisDemoUserController.java
│           └── resources
│               ├── static
│               │   └── index.html
│               └── templates
│                   ├── greeting.html
│                   └── greeting2.html
└── start
    ├── pom.xml
    └── src
        ├── main
        │   ├── java
        │   │   └── com
        │   │       └── yodean
        │   │           └── project
        │   │               └── ProjectApplication.java
        │   └── resources
        │       ├── application.properties
        │       ├── static
        │       └── templates
        └── test
            └── java
                └── com
                    └── yodean
                        └── project
                            └── ProjectApplicationTests.java
  • project-model: 属于Model层,包含了数据库操作(通过Mybatis简化持久层操作)和数据模型。「包mybatis」就是DAO层,有实体、配置、Mapper。User.java 就是领域对象。
  • project-service: 业务的封装,依赖项目 project-model,属于Model层和Contrller层
@Service
public class GetUserInfoServiceImpl implements GetUserInfoService{

    @Autowired
    protected MVCMybatisDemoUserMapper mVCMybatisDemoUserMapper;

    @Override
    public void getUserInfoById(String id, Model model)
    {


        //search by id, get UserInfo
        MVCMybatisDemoUser user = mVCMybatisDemoUserMapper.queryUserInfo(id);
        model.addAttribute("name", user.getId())
                .addAttribute("age", user.getAge())
                .addAttribute("height", user.getHeight())
                .addAttribute("weight", user.getWeight());
    }
}
  • project-web: 类Controller属于controller层。templates下的文件是View层,使用 thymeleaf 模版技术。
@RestController
@RequestMapping("/usermybatis")
public class MybatisDemoUserController {

    @Autowired
    private MybatisDemoUserMapper mybatisDemoUserMapper;

    @Autowired
    private GetUserInfoService getUserInfoService;

    // http://127.0.0.1:8080/usermybatis/findAll
    @RequestMapping("/findAll")
    public List<MybatisDemoUser> findAll(){
        return mybatisDemoUserMapper.findAll();
    }

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="1") String name, Model model) {
        getUserInfoService.getUserInfoById(name, model);
        //这里返回的数据类型是String,但实际上更多的数据通过本函数中Model model传给了前端。返回值String也会被SpringMVC整合为一个ModelAndView,以供前端使用。(Controller可以返回多种数值,比如void、String、ModelAndView。同学们可以自行搜索学习)
        return "greeting";
    }

}

Controller层可以直接依赖model层,操作数据。

  • start:项目启动配置

MVC架构的特点

数据与视图分离,但是业务代码复用性不高,适合前后端不分离的小项目。

分层架构

架构项目依赖

http://xhope.top/wp-content/uploads/2021/09/a2.png

  • project-dao:数据访问层,与底层 MySQL、Oracle、Hbase、OB 等进行数据交互。对应MVC中的Model层,属于基础设施层。
└── com
    └── yodean
        └── project
            ├── dao
            │   ├── dataobject
            │   │   └── UserDO.java
            │   └── mapper
            │       └── UserMapper.java
            └── mybatis
                ├── config
                │   └── MybatisDemoConfig.java
                ├── entity
                │   └── MybatisDemoUser.java
                └── mapper
                    └── MybatisDemoUserMapper.java

1.包dao:

DO: 此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象

Mapper: 仓库持久化

2.包mybatis:

entity: Mybatis配置类

entity: 领域对象,数据库可能是一个join查询

Mapper: 仓库持久化

  • project-manager:通用业务处理层,依赖DAO层。它有如下特征:
    1) 对第三方平台封装的层,预处理返回结果及转化异常信息,适配上层接口。
    2) 对 Service 层通用能力的下沉,如缓存方案、中间件通用处理。
    3) 与 DAO 层交互,对多个 DAO 的组合复用。

  • project-api:业务逻辑服务层接口层。

└── com
    └── yodean
        └── project
            └── api
                ├── UserService.java
                └── model
                    └── UserModel.java

UserService.java

public interface UserService {
    String getUserName(Long id);
    UserModel addUser(UserModel user);
}

UserModel: 属于DTO对象

  • project-service:相对具体的业务逻辑服务实现层。依赖dao层、manager层、api层。
└── com
    └── yodean
        └── project
            └── service
                └── UserServiceImpl.java

UserServiceImpl.java

@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    private static final BeanCopier copier = BeanCopier.create(UserModel.class, UserDO.class, false);

    public String getUserName(Long id) {
        UserDO userDO = userMapper.getById(id);
        return userDO != null ? userDO.getName() : null;
    }

    public UserModel addUser(UserModel user) {
        UserDO userDO = new UserDO();
        copier.copy(user, userDO, null);
        Long id = userMapper.insert(userDO);
        user.setId(id);
        return user;
    }
}

实现了模块api的接口 UserService ,并依赖模块dao做持久化操作 UserMapper

  • project-web:网关适配层,依赖dao层、api层。
└── com
    └── yodean
        └── project
            ├── mybatis
            │   └── controller
            │       └── MybatisDemoUserController.java
            └── web
                └── UserController.java

UserController.java

@Component
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/username")
    public String getUserName(@RequestParam("id") Long id) {
        return userService.getUserName(id);
    }
    @RequestMapping("/add")
    @ResponseBody
    public UserModel addUser(@RequestParam("name") String name, @RequestParam("age") Integer age) {
        UserModel user = new UserModel();
        user.setName(name);
        user.setAge(age);
        return userService.addUser(user);
    }
}

Web层可以直接依赖dao层,操作数据。

  • start: 项目启动配置,项目装配。

分层架构的特点

数据与视图分离,业务代码复用性高,适合前后端分离的项目。

阿里巴巴Java开发推荐分层结构如图所示

https://raw.githubusercontent.com/alibaba/p3c/p3c-pmd-2.1.0/p3c-gitbook/images/alibabaLevel.png

领域驱动COLA架构

DDD以业务为核心,解耦外部依赖,分离业务复杂度和技术复杂度。
DDD的架构模式有六边形架构、洋葱圈架构、整洁架构、COLA架构等。
COLA项目地址:https://github.com/alibaba/COLA
COLA参考资料:COLA 4.0:应用架构的最佳实践

COLA架构图

http://xhope.top/wp-content/uploads/2021/09/a3.png
由图所示,COLA架构采用了4层架构。Adapter层(用户接口层),App 层(应用层),Domain层(领域层),Infrastructure层(基础设施层)。

架构项目依赖

http://xhope.top/wp-content/uploads/2021/09/a4.png

  • project-controller:适配层(Adapter Layer),负责对前端展示(web,wireless,wap)的路由和适配,对于传统B/S系统而言,adapter就相当于MVC中的controller
  • project-app:应用层(Application Layer),主要负责获取输入,组装上下文,参数校验,调用领域层做业务处理,如果需要的话,发送消息通知等。层次是开放的,应用层也可以绕过领域层,直接访问基础实施层;
  • project-client:Client SDK,服务对外透出的API;
  • project-domain:领域层(Domain Layer),主要是封装了核心业务逻辑,并通过领域服务(Domain Service)和领域对象(Domain Entity)的方法对App层提供业务实体和业务逻辑计算。领域是应用的核心,不依赖任何其他层次;
  • project-infrastructure:基础实施层(Infrastructure Layer),主要负责技术细节问题的处理,比如数据库的CRUD、搜索引擎、文件系统、分布式服务的RPC等。此外,领域防腐的重任也落在这里,外部依赖需要通过gateway的转义处理,才能被上面的App层和Domain层使用。

DDD-经典四层架构应用
通过现实例子显示领域驱动设计的威力

源代码下载

architecture.zip

PO BO DTO VO DO的区别

  • DO(Data Object):此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象。
  • DTO(Data Transfer Object):数据传输对象,Service 或 Manager 向外传输的对象。
  • BO(Business Object):业务对象,可以由 Service 层输出的封装业务逻辑的对象。
  • Query:数据查询对象,各层接收上层的查询请求。注意超过 2 个参数的查询封装,禁止使用 Map 类 来传输。
  • VO(View Object):显示层对象,通常是 Web 向模板渲染引擎层传输的对象。

更多参考:

看懂UML类图

类之间到关系

  • 泛化关系
  • 实现关系
  • 聚合关系
  • 组合关系
  • 关联关系
  • 依赖关系

泛化关系

继承关系为 is-a的关系;两个对象之间如果可以用 is-a 来表示,就是继承关系:(..是..)

eg:自行车是车、猫是动物

泛化关系用一条带空心箭头的直接表示;如下图表示(A继承自B);

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_generalization.jpg

最终代码实现:泛化关系 表现为「继承(extend)」。

public class A {

}

public class B extend A {

}
public interface A {

}

public interface B extend A {

}

实现关系

实现关系用一条带空心箭头的虚线表示;

eg:”车”为一个抽象概念,在现实中并无法直接用来定义对象;只有指明具体的子类(汽车还是自行车),才 可以用来定义对象(”车”这个类在C++中用抽象类表示,在JAVA中有接口这个概念,更容易理解)

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_realize.jpg

最终代码实现:实现关系 表现为「实现(implements)」。

public interface A {

}

public class B implements A {

}

聚合关系

聚合关系用一条带空心菱形箭头的直线表示,如下图表示A聚合到B上,或者说B由A组成;

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_aggregation.jpg

聚合关系用于表示实体对象之间的关系,表示整体由部分构成的语义;例如一个部门由多个员工组成;

与组合关系不同的是,整体和部分「不是强依赖」的,即使整体不存在了,部分仍然存在;例如, 部门撤销了,人员不会消失,他们依然存在;

最终代码实现:聚合关系 表现为「类属性」。

public class Department {

}

public class User {
    private Department department;
}

组合关系

组合关系用一条带实心菱形箭头直线表示,如下图表示A组成B,或者B由A组成;

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_composition.jpg

与聚合关系一样,组合关系同样表示整体由部分构成的语义;比如公司由多个部门组成;

但组合关系是一种「强依赖」的特殊聚合关系,如果整体不存在了,则部分也不存在了;例如, 公司不存在了,部门也将不存在了;

最终代码实现:聚合关系 表现为「类属性」。

public class Address {

}

public class User {
    private Address address;
}

关联关系

关联关系是用一条直线表示的;它描述不同类的对象之间的结构关系;它是一种静态关系, 通常与运行状态无关,一般由常识等因素决定的;它一般用来定义对象之间静态的、天然的结构; 所以,关联关系是一种「强关联」的关系;

比如,乘车人和车票之间就是一种关联关系;学生和学校就是一种关联关系;

关联关系默认不强调方向,表示对象间相互知道;如果特别强调方向,如下图,表示A知道B,但 B不知道A;

关联关系分为:单向关联和双向关联

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_association.jpg

最终代码实现:关联关系 表现为「类属性」。

public class School {
    private Set<Student> students;
}

public class Student {
    private School school;
}

依赖关系

依赖关系是用一套带箭头的虚线表示的;如下图表示A依赖于B;他描述一个对象在运行期间会用到另一个对象的关系;

https://design-patterns.readthedocs.io/zh_CN/latest/_images/uml_dependency.jpg

与关联关系不同的是,它是一种临时性的关系,通常在运行期间产生,并且随着运行时的变化; 依赖关系也可能发生变化;

显然,依赖也有方向,双向依赖是一种非常糟糕的结构,我们总是应该保持单向依赖,杜绝双向依赖的产生(Spring注入到时候不要循环依赖);

注:在最终代码中,依赖关系体现为类构造方法及类方法的传入参数,箭头的指向为调用关系;依赖关系除了临时知道对方外,还是“使用”对方的方法和属性;

public class A {

}

public class B {

    public void fun(A a) {

    }
}

以订单为例的综合类图

http://xhope.top/wp-content/uploads/2021/09/22.png

参考:
https://design-patterns.readthedocs.io/zh_CN/latest/
https://www.cnblogs.com/uml-tool/p/8568396.html