将数据保存到数据库〜时得到“java.lang.NullPointerException”

时间:2013-10-04 04:34:57

标签: java swing hibernate

我做了一个项目从csv文件插入数据,但是我遇到了一些问题" java.lang.NullPointerException"使用hibernate将数据保存到数据库时,

这是我的代码〜

public void LoadData() throws Exception{
    String csvFile = validatePath(txtPath.getText().toString());
    BufferedReader br = null;
    String line = "";
    String csvSplitBy = ";";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null){

            //pake ";" sebagai delimiter
            String [] cs        = line.split(csvSplitBy);
            String module       = cs[0].replaceAll("\\W", "");
            //String module     = cs[0].substring(1);
            String system_id    = cs[1];
            String object       = cs[2];
            String tgl1         = cs[3];
            String tgl2         = cs[4].substring(0, cs[4].length() - 1);

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            Date log_date = sdf1.parse(tgl1);

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            Date update_log = sdf2.parse(tgl2);

            CoreService data = new CoreService();
            data.setMODULE_NAME(module);
            data.setSYSTEM_ID(system_id);
            data.setOBJECT_NAME(object);
            data.setLOG_DATE(log_date);
            data.setUPDATE_LOG(update_log);
            data.setCATEGORY("SYSTEMID");
            data.setCOUNTER_SERVICE(1);
            data.setCOUNTER_SYSTEM(1);

            System.out.println(data);

            core.save(data);
            System.out.println(module);
            System.out.println(module+" ~ "+system_id+" ~ "+object+" ~ "+log_date+" ~ "+update_log);
        }

    } catch (FileNotFoundException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (IOException e){
         e.printStackTrace();
    } finally {
        if (br != null){
            try{
                br.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    System.out.println("sukses");

}

这个错误:

java.lang.NullPointerException
at id.co.bni.coreservice.controller.CoreServiceController.LoadData(CoreServiceController.java:222)
at id.co.bni.coreservice.controller.CoreServiceController.actionPerformed(CoreServiceController.java:145)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

任何帮助都会很愉快, 提前谢谢:)

我只是想展示我的完整代码,所以我可以解决我的问题〜

package id.co.bni.coreservice.controller;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
import java.io.File;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.table.DefaultTableModel;//package table

import org.springframework.beans.factory.annotation.Autowired;

import id.co.bni.coreservice.service.CoreServiceService;
import id.co.bni.coreservice.model.CoreService;

@SuppressWarnings("serial")
public class CoreServiceController extends JFrame implements ActionListener,
    FocusListener, MouseListener {

@Autowired CoreServiceService core;

// deklarasi objek
private Dimension UM = Toolkit.getDefaultToolkit().getScreenSize();

private JPanel CoreService = new JPanel();
private JLabel lblPath = new JLabel("PATH");
private JTextField txtPath = new JTextField();

private JButton cmdBrowse = new JButton("Browse");
private JButton cmdLoad = new JButton("Load Data");
private JButton cmdReset = new JButton("Reset");

// deklarasi panel Alas
private JPanel pnlALAS = new JPanel();

// deklarasi objek tabel
String[] strJdl = { "MODULE_NAME", "CATEGORY", "SYSTEM_ID",
        "COUNTER_SYSTEM", "OBJECT_NAME", "COUNTER_SERVICE", "LOG_DATE",
        "UPDATE_LOG" };
DefaultTableModel tabMode;
JTable tabel = new JTable();
JScrollPane skrTabel = new JScrollPane();

// Deklarasi Metode, Function, atau prosedur (deklarasi setbound)
public CoreServiceController() {
    setSize(1050, 520); // width,hight
    setLocation(UM.width / 2 - getWidth() / 2, UM.height / 2 - getHeight()
            / 2); // x(jarak monitor kelayar dari samping ),y(dari bawah
                    // atas layar monitor)
    setTitle("Load Data CSV to Oracle");
    // set default close operation
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    CoreService.setLayout(null);

    lblPath.setBounds(195, 15, 150, 25);
    txtPath.setBounds(250, 15, 400, 25);

    // tabel
    skrTabel.setBounds(25, 90, 985, 380);

    cmdBrowse.setBounds(670, 15, 80, 25);
    cmdReset.setBounds(770, 15, 80, 25);
    cmdLoad.setBounds(440, 50, 120, 30);

    // ===================================================
    pnlALAS.setLayout(null);
    pnlALAS.add(lblPath);
    pnlALAS.add(txtPath);

    pnlALAS.add(cmdBrowse);
    pnlALAS.add(cmdLoad);
    pnlALAS.add(cmdReset);
    pnlALAS.add(skrTabel);

    getContentPane().add(pnlALAS);
    inisialisasi();
    setVisible(true);

    // instansiasi objek tabel
    tabMode = new DefaultTableModel(null, strJdl) {
        public boolean isCellEditable(int row, int col)

        {
            if (col >= 0)
                return false;
            else
                return true;
        }
    };
    tabel.setModel(tabMode);
    skrTabel.getViewport().add(tabel);
    tabel.setEnabled(true);

    tabel.addMouseListener(this);

    txtPath.addFocusListener(this);

    cmdBrowse.addActionListener(this);
    cmdLoad.addActionListener(this);
    cmdReset.addActionListener(this);

    inisialisasi();
    // setVisible(true);
    setVisible(true);

}

void inisialisasi() {
    // menonaktifkan komponen
    txtPath.setEnabled(true);

    cmdBrowse.setEnabled(true);
    cmdLoad.setEnabled(false);
    cmdReset.setEnabled(false);

    // membersihkan komponen
    txtPath.setText("");

    txtPath.requestFocus();

}

public void actionPerformed(ActionEvent splatter) {
    if (splatter.getSource() == cmdBrowse) {
        browseCSV();
        cmdReset.setEnabled(true);
        cmdLoad.setEnabled(true);
    }
    if (splatter.getSource() == cmdLoad) {
        try {
            LoadData();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (splatter.getSource() == cmdReset) {
        inisialisasi();
    }
}

private void browseCSV() {
    JFileChooser jfc = new JFileChooser();
    FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File f) {
            if (f.getName().toLowerCase().endsWith(".csv")
                    || f.isDirectory()) {
                return true;
            } else {
                return false;
            }
        }
        @Override
        public String getDescription() {
            return "*.csv";
        }
    };

    jfc.addChoosableFileFilter(fileFilter);
    jfc.setMultiSelectionEnabled(false);
    jfc.showOpenDialog(this);
    // mengambil path file
    String path = jfc.getSelectedFile().getAbsolutePath();
    txtPath.setText(path);
}

public void LoadData() throws Exception{
    String csvFile = validatePath(txtPath.getText().toString());
    BufferedReader br = null;
    String line = "";
    String csvSplitBy = ";";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null){

            //pake ";" sebagai delimiter
            String [] cs        = line.split(csvSplitBy);
            String module       = cs[0].replaceAll("\\W", "");
            //String module     = cs[0].substring(1);
            String system_id    = cs[1];
            String object       = cs[2];
            String tgl1         = cs[3];
            String tgl2         = cs[4].substring(0, cs[4].length() - 1);

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            Date log_date = sdf1.parse(tgl1);

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            Date update_log = sdf2.parse(tgl2);

            CoreService data = new CoreService();
            data.setMODULE_NAME(module);
            data.setSYSTEM_ID(system_id);
            data.setOBJECT_NAME(object);
            data.setLOG_DATE(log_date);
            data.setUPDATE_LOG(update_log);
            data.setCATEGORY("SYSTEMID");
            data.setCOUNTER_SERVICE(1);
            data.setCOUNTER_SYSTEM(1);

            System.out.println(data);

            core.save(data);
            System.out.println(module);
            System.out.println(module+" ~ "+system_id+" ~ "+object+" ~ "+log_date+" ~ "+update_log);
        }

    } catch (FileNotFoundException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (IOException e){
         e.printStackTrace();
    } finally {
        if (br != null){
            try{
                br.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    System.out.println("sukses");

}

private String validatePath(String invalidPath) {
    String validPath;
    validPath = invalidPath.replace('\\', '/');
    return validPath;
}

/**
 * @param args
 */
public static void main(String[] args) {
    new CoreServiceController();
}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void focusGained(FocusEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void focusLost(FocusEvent e) {
    // TODO Auto-generated method stub

}

}

0 个答案:

没有答案