차트에 데이터 반영이 제대로 안돼는것 같습니다.

조회수 695회

Mapper:

package kr.co.allday.bean;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class TransectionBean {

    private String transactionnum;
    private int transactionamount;
    private String membernum;
    private String inventorynum;
    private String storeid;

}

========================================================= DAO:

package kr.co.allday.dao;

import kr.co.allday.bean.TransectionBean;
import kr.co.allday.mapper.TransectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TransectionDAO {

    private final TransectionMapper transectionMapper;

    @Autowired
    public TransectionDAO(TransectionMapper transectionMapper) {
        this.transectionMapper = transectionMapper;
    }

    public List<TransectionBean> getTransectionList() {
        return transectionMapper.getTransectionList();
    }
}

=========================================================

Service:

package kr.co.allday.service;

import kr.co.allday.bean.TransectionBean;
import kr.co.allday.dao.TransectionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TransectionService {

    private final TransectionDAO transectionDAO;

    @Autowired
    public TransectionService(TransectionDAO transectionDAO) {
        this.transectionDAO = transectionDAO;
    }

    public List<TransectionBean> getTransectionList() {
        return transectionDAO.getTransectionList();
    }


}

============================================================ Controller:

package kr.co.allday.controller;

import kr.co.allday.bean.TransectionBean;
import kr.co.allday.service.TransectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class TransectionController {

    private TransectionService transectionService;

    @Autowired
    public TransectionController(TransectionService transectionService) {
        this.transectionService = transectionService;
    }

 // TransectionController.java
    @GetMapping("/transactionList")
    public String getTransactionList(Model model) {
        // Get transaction list from service
        List<TransectionBean> transactionList = transectionService.getTransectionList();

        // Add transaction list to the model with the correct name
        model.addAttribute("transectionListJson", transactionList);

        // Return the view name
        return "owner_salse";
    }

}

============================================================

구글차트를 사용하여 다음과 같이 작성해 뷰에 출력하려 했습니다. 차트는 뷰로 넘어오면 자동으로 실행되게 하였습니다.

var transectionList = $(transectionList); // transectionListJson은 모델에 담긴 데이터의 이름입니다.

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var chartData = new google.visualization.DataTable();
    chartData.addColumn('string', 'storeid');
    chartData.addColumn('number', 'salse');

    // 서버에서 받아온 데이터를 DataTable에 추가
    for (var i = 0; i < transectionList.length; i++) {
        chartData.addRow([transectionList[i].storeid, transectionList[i].transactionamount]);
    }

    var options = {'title':'매출 현황',
                   'width':400,
                   'height':300};

    var chart = new google.visualization.BarChart(document.getElementById('result-chart'));
    chart.draw(chartData, options);
}

그런데 이때 차트가  형식은 나오는데 막대 바가 나오지 않습니다.





1 답변

  • 현상만 보지 마시고 어디서 문제가 나왔는지 체크해 보셔야 합니다.

    Jquery 로 model 에 들어있는 객체를 바로 가져올 수 있나요? transectionList 는 json 형식인가요?

    controller.java

    @Controller
    public class DemoController {
    
        @GetMapping("/chart")
        public String mapChart() {
            return "chart";
        }
    
        @ResponseBody
        @GetMapping("/getdata")
        public ArrayList<DemoData> getData(){
            ArrayList<DemoData> list = new ArrayList<>();
            list.add(new DemoData(1, 100, "test1"));
            list.add(new DemoData(2, 150, "test2"));
            return list;
        }
    }
    
    /**
     * DemoData
     */
    class DemoData {
        private int id;
        private int sales;
        private String comment;
    
        public DemoData(int id, int sales, String comment) {
            this.id = id;
            this.sales = sales;
            this.comment = comment;
        }
    
        public int getId() {
            return id;
        }
        ...생략...
    
    }
    

    templates/chart.index

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <!--Load the AJAX API-->
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">
    
            // Load the Visualization API and the corechart package.
            google.charts.load('current', { 'packages': ['corechart'] });
    
            // Set a callback to run when the Google Visualization API is loaded.
            google.charts.setOnLoadCallback(drawChart);
    
            // Callback that creates and populates a data table,
            // instantiates the pie chart, passes in the data and
            // draws it.
            function drawChart() {
    
                // Fetch data from '/getdata' .
                fetch("./getdata").then(cd => cd.json())
                    .then(json => {
                        // Create the data table.
                        let data = new google.visualization.DataTable();
                        data.addColumn('number', 'Topping');
                        data.addColumn('number', 'Slices');
                        console.log(json.length)
                        for (let i = 0; i < json.length; i++) {
                            console.log(json[i]);
                            data.addRows([
                                [json[i].id, json[i].sales],
                            ]);
                        }
    
                        // Set chart options
                        var options = {
                            'title': '매출 현황',
                            'width': 500,
                            'height': 300
                        };
    
                        // Instantiate and draw our chart, passing in some options.
                        var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
                        chart.draw(data, options);
                    }
                    );
            }
        </script>
    </head>
    <body>
        Reach for the summit!<br>
        <hr>
        <div id="chart_div"></div>
        <hr>
    </body>
    </html>
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)