You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring项目DevExpress表格:如何替换data.js为SQL Server数据库数据

Hey there! Let's walk through how to swap out that static data.js content with real SQL Server data in your Spring + DevExpress + jQuery setup. I'll break this down into clear, actionable steps:

1. Build a Spring Backend API to Fetch SQL Server Data

First, we need to create backend components to connect to your SQL Server database and expose the order data via a REST endpoint.

1.1 Create an Entity Class

This class maps directly to your SQL Server orders table (adjust the table/column names to match your actual database schema):

import javax.persistence.*;

@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer ID;
    private Integer OrderNumber;
    private String OrderDate;
    private String DeliveryDate;
    private Double SaleAmount;
    private String Terms;
    private String CustomerStoreCity;
    private String Employee;

    // Required: No-arg constructor, all-arg constructor, and getter/setter methods for all fields
}

1.2 Create a Repository Interface

Use Spring Data JPA to handle database queries with minimal code:

import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, Integer> {
    // The default `findAll()` method will fetch all orders for us
}

Separate business logic from the controller for better maintainability:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class OrderService {
    private final OrderRepository orderRepository;

    @Autowired
    public OrderService(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }
}

1.4 Create a REST Controller

Expose an endpoint to return order data as JSON:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping
    public List<Order> getOrders() {
        return orderService.getAllOrders();
    }
}

1.5 Configure SQL Server Connection

Add these settings to your application.properties file (replace placeholders with your database details):

spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=YourDatabaseName;encrypt=true;trustServerCertificate=true
spring.datasource.username=your_db_username
spring.datasource.password=your_db_password
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
2. Update Frontend to Load Data from the API

Now we'll replace the static orders array with a dynamic API call using jQuery.

2.1 Adjust data.js (or Remove It)

You can either delete the static var orders = [...] line from data.js, or repurpose it to hold the fetched data later. For simplicity, we'll handle the data fetch directly in index.js.

2.2 Modify index.js to Fetch Data

Update your DevExpress DataGrid initialization to use jQuery's ajax method to pull data from the backend:

$(function() {
    // Fetch data from the Spring API
    $.ajax({
        url: "/api/orders",
        method: "GET",
        dataType: "json",
        success: function(fetchedOrders) {
            // Initialize DevExpress DataGrid with the fetched data
            $("#gridContainer").dxDataGrid({
                dataSource: fetchedOrders,
                columns: [
                    { dataField: "ID" },
                    { dataField: "OrderNumber" },
                    { dataField: "OrderDate", dataType: "date" },
                    { dataField: "DeliveryDate", dataType: "datetime" },
                    { dataField: "SaleAmount", format: "currency" },
                    { dataField: "Terms" },
                    { dataField: "CustomerStoreCity" },
                    { dataField: "Employee" }
                ],
                // Keep your existing DevExpress config (filtering, pagination, etc.)
                filtering: { mode: "row" },
                paging: { pageSize: 10 },
                pager: {
                    showPageSizeSelector: true,
                    allowedPageSizes: [5, 10, 20]
                }
            });
        },
        error: function(xhr, status, error) {
            console.error("Failed to load order data:", error);
            alert("Oops! Couldn't load order data. Check if the backend is running correctly.");
        }
    });
});
3. Key Notes to Avoid Issues
  • CORS Configuration: If your frontend and backend ever run on different ports (e.g., frontend on 8080, backend on 8081), add cross-origin support in Spring. You can annotate the OrderController with @CrossOrigin(origins = "http://your-frontend-url") or set up a global CORS config.
  • Date Format Matching: Ensure the date strings returned from SQL Server align with what DevExpress expects. If using Date types in your entity, Spring will return ISO-format dates (e.g., 2017-04-13T09:00:00), which DevExpress can parse automatically.
  • Test the API First: Before debugging the frontend, visit http://localhost:8080/api/orders in your browser to confirm it returns valid JSON data.

内容的提问来源于stack exchange,提问作者BENHASSINE MohamedFourat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:42:49