Creating Hibernate project storing .csv file data into the database

    Creating Hibernate project storing .csv file data into the database


code for reading .csv file and creating SessionFactory and Session object and saving student object into the database.

public class App {
    public static void main(String args[]) {
        String csvFilePath = "C:\\Users\\kalas\\OneDrive\\Desktop\\Student.csv";
        try {
            BufferedReader lineReader = new BufferedReader(new FileReader(csvFilePath));
            CSVParser records = CSVParser.parse(lineReader, CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());

            SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
            Session session = factory.openSession();
            session.beginTransaction();
            for (CSVRecord record : records) {
                Student student = new Student();
                student.setStudentId(Integer.parseInt(record.get(0)));
                student.setStudentName(record.get(1));
                session.save(student);

            }
            session.getTransaction().commit();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}


Related Videos:-




No comments

Powered by Blogger.