JAVA:先后从数据库拿出相同数据生成对象,对象是同一个

最近在写项目的时候遇到一个问题,用for修改数据库中拿到的对象时:

List<OrderForm> orderForms = orderFormMapper.selectByUerId(account);
//从数据库中拿到数据,生成对象列表
        for(int i=0;i<orderForms.size();i++){
        List<ShoppingCarToGoods> shoppingCarToGoods = orderForms.get(i).getGoodsList();
           for(int j=0;j<shoppingCarToGoods.size(); j++){
               Price price = shoppingCarToGoods.get(j).getPrice();
                 price.setBuyNum(shoppingCarToGoods.get(j).getBuyNum);
                    //这里修改信息
           }
       }

得到的结果中部分Price对象的buyNum总是和我设置的值不一样,

这是拿到Price对象的语句:

<select id="getPrice" resultType="Price" parameterType="java.lang.String" >
  select id,price,unit,num,weight from tb_price where id=#{priceId,jdbcType=VARCHAR}
</select>

后来观察结果的时候发现,查询拿到的一部分数据中信息是全部一样的,这些属性值一样的对象可能是同一个对象。

打印相同信息的对象:

 if(price.getId().equals("11"))System.out.println(price);

 结果:

com.yidong.model.Price@3c437886
com.yidong.model.Price@3c437886

证明这两个先后拿出的对象是同一个。

结论:

所以for循环中修改的是同一个对象,后修改的部分覆盖了前面修改的部分。

解决方法:每次拿到数据后,自己new一个新的对象并赋值:

for(int i=0;i<orderForms.size();i++){
          shoppingCarToGoods = orderForms.get(i).getGoodsList();
           for(int j=0;j<shoppingCarToGoods.size(); j++){
               Price price = shoppingCarToGoods.get(j).getPrice();           
               Price newPrice = new Price();
               //这里必须new一个新的price对象,因为相同的priceId拿出来的price对象是同一个,
               // 也就是说假如订单A和订单B的包含同一件商品、同一个priceId,那么拿出来的price对象是同一个
               //这时候先修改订单A中price的buyNum,订单B后面也修改了相同price的buyNum,最后订单A中显示的是订单B的buyNum
               newPrice.setId(price.getId());
               newPrice.setNum(price.getNum());
               newPrice.setPrice(price.getPrice());
               newPrice.setUnit(price.getUnit());
               newPrice.setWeight(price.getWeight());
               newPrice.setBuyNum(shoppingCarToGoods.get(j).getBuyNum());
               shoppingCarToGoods.get(j).setPrice(newPrice);
           }
       }

 

### 回答1: 在Java中可以使用Apache POI库来生成Excel表格并设置样式。首先,需要添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 以下是一个简单的示例,演示如何生成一个有格式且可改变样式的Excel表,并将数据从数据库写入其中: ```java import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelGenerator { public static void main(String[] args) throws SQLException, IOException { // 从数据库获取数据 String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "password"; Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM mytable"); ResultSet rs = stmt.executeQuery(); // 创建工作簿和工作表 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("My Sheet"); // 创建样式和字体 CellStyle headerCellStyle = workbook.createCellStyle(); headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerCellStyle.setAlignment(HorizontalAlignment.CENTER); Font headerFont = workbook.createFont(); headerFont.setBold(true); headerCellStyle.setFont(headerFont); // 创建标题行 Row headerRow = sheet.createRow(0); String[] headers = {"ID", "Name", "Email"}; for (int i = 0; i < headers.length; i++) { String header = headers[i]; headerRow.createCell(i).setCellValue(header); headerRow.getCell(i).setCellStyle(headerCellStyle); } // 填充数据 int rowNum = 1; while (rs.next()) { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(rs.getInt("id")); row.createCell(1).setCellValue(rs.getString("name")); row.createCell(2).setCellValue(rs.getString("email")); } // 调整列宽 sheet.autoSizeColumn(0); sheet.autoSizeColumn(1); sheet.autoSizeColumn(2); // 保存工作簿到文件 FileOutputStream fileOut = new FileOutputStream("myexcel.xlsx"); workbook.write(fileOut); fileOut.close(); workbook.close(); // 生成前端页面并添加下载按钮 // 略 } } ``` 在上述代码中,我们首先从数据库中获取数据。然后,我们创建一个XSSFWorkbook对象表示工作簿,创建一个Sheet对象表示工作表。接着, ### 回答2: 要用Java生成一个有格式且可改变样式的Excel表,可以使用Apache POI库来实现。首先,我们需要添加POI的相关依赖。 ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,我们来生成Excel表并从数据库中获取数据写入表中。 ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.sql.*; public class ExcelGenerator { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/database_name"; String username = "your_username"; String password = "your_password"; try (Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name")) { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 设置表头样式 CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerStyle.setAlignment(HorizontalAlignment.CENTER); // 创建表头 Row headerRow = sheet.createRow(0); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { Cell cell = headerRow.createCell(i - 1); cell.setCellValue(metaData.getColumnName(i)); cell.setCellStyle(headerStyle); } // 设置数据样式 CellStyle dataStyle = workbook.createCellStyle(); dataStyle.setAlignment(HorizontalAlignment.CENTER); // 写入数据 int rowNum = 1; while (resultSet.next()) { Row row = sheet.createRow(rowNum++); for (int i = 1; i <= columnCount; i++) { Cell cell = row.createCell(i - 1); cell.setCellValue(resultSet.getString(i)); cell.setCellStyle(dataStyle); } } // 保存Excel文件 try (FileOutputStream fileOutputStream = new FileOutputStream("data.xls")) { workbook.write(fileOutputStream); } System.out.println("Excel生成成功!"); } catch (SQLException | IOException e) { e.printStackTrace(); } } } ``` 以上代码会从数据库中查询数据,并将数据写入Excel表中并保存为"data.xls"文件。 接下来,我们需要生成与之关联的前端页面用于下载Excel表的按钮。 ```html <!DOCTYPE html> <html> <head> <title>Excel下载</title> </head> <body> <button onclick="downloadExcel()">下载Excel表</button> <script type="text/javascript"> function downloadExcel() { window.location.href = "http://localhost:8080/downloadExcel"; } </script> </body> </html> ``` 在上面的代码中,我们创建了一个按钮,当点击该按钮时,会通过调用下载Excel表的接口。 最后,我们需要创建一个用于下载Excel表的Java接口。 ```java import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; @WebServlet("/downloadExcel") public class ExcelDownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = "data.xls"; response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + filePath); try (FileInputStream fileInputStream = new FileInputStream(new File(filePath)); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[1024]; int length; while ((length = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } outputStream.flush(); } } } ``` 在上述代码中,我们通过设置响应头来实现文件下载,并将生成的Excel表作为输出流写入响应中。 以上就是使用Java生成一个有格式且可改变样式的Excel表,并将数据从数据库写入Excel表中,并生成与之关联的前端页面,点击按钮可以下载该Excel表到本地的实现步骤。 ### 回答3: 要用Java生成一个有格式且可改变样式的Excel表格,并从数据库中获取数据写入该表格,可以使用Apache POI库。下面是一个简单的实现步骤: 1. 导入所需的POI库依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个新的Excel工作簿对象: ```java Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("数据表"); ``` 3. 设置表格样式: ```java CellStyle headerStyle = workbook.createCellStyle(); Font headerFont = workbook.createFont(); headerFont.setBold(true); headerStyle.setFont(headerFont); // 设置其他样式,如背景色、边框等,可以使用CellStyle的各种方法来设置 ``` 4. 写入表头行: ```java Row headerRow = sheet.createRow(0); Cell headerCell = headerRow.createCell(0); headerCell.setCellValue("列1"); headerCell.setCellStyle(headerStyle); // 创建其他列,设置值和样式,可以使用循环来处理多列的情况 ``` 5. 从数据库中获取数据,循环写入表格的数据行: ```java List<Data> dataList = getDataFromDatabase(); // 从数据库中获取数据 int rowIndex = 1; // 从第二行开始写入数据 for (Data data : dataList) { Row dataRow = sheet.createRow(rowIndex); Cell dataCell = dataRow.createCell(0); dataCell.setCellValue(data.getValue()); // 创建其他列,设置值和样式 rowIndex++; } ``` 6. 生成前端页面,添加一个按钮用于下载Excel表格: ```html <button onclick="downloadExcel()">下载Excel表格</button> <script> function downloadExcel() { window.location.href = "/downloadExcel"; // 调用后端接口下载Excel表格 } </script> ``` 7. 后端编写接口,将生成的Excel表格以文件流形式输出给前端: ```java @RestController public class ExcelController { @GetMapping("/downloadExcel") public ResponseEntity<InputStreamResource> downloadExcel() throws Exception { // 生成Excel文件,参考上述的代码逻辑 // ... ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=data.xlsx"); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) .body(new InputStreamResource(inputStream)); } } ``` 这样就实现了在Java生成一个有格式且可改变样式的Excel表格,并从数据库中获取数据写入该表格,并提供了一个前端页面供用户点击按钮下载该Excel表格到本地。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值