我想读取Excel文件并将数据上传到PostgresDB中的表中

时间:2014-05-08 12:40:17

标签: java excel hibernate postgresql

模型类

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name="employee_details")
    public class Employee {
@Id
@Column(name="emp_id")
private int id;
@Column(name="emp_name")
private String name;
@Column(name="location")
private String location;


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getLocation() {
    return location;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public void setLocation(String location) {
    this.location = location;
}
    }

主类

    public class ReadExcel {
static List<Employee>empList = new ArrayList<Employee>();

public static void main(String[] args){


        List<Employee>employees=readExcel("D:\\test.xls");
        persistToDB(employees);
}



private static List<Employee> readExcel(String filepath) {
    try {
        FileInputStream file = new FileInputStream(new      
    File("D:\\test.xls"));

        // Getting the instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(file);

        // Get First sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);

        ArrayList myList = new ArrayList();
        // Iterate start from the first sheet of the uploaded excel file
        Iterator<Row> rowIterator = sheet.iterator();
        Employee employee = new Employee();


        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            if (row.getRowNum() == 0) {
                continue;// skip to read the first row of file
            }

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                if (cell.getColumnIndex() == 0 ) {
                    employee.setId((int)        cell.getNumericCellValue());
                    empList.add(employee);
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                }
                else if (cell.getColumnIndex() == 1 ) {
                    employee.setName(cell.getStringCellValue());
                    empList.add(employee);
                    System.out.print(cell.getStringCellValue() + "\t\t");
                }
                else if (cell.getColumnIndex() == 2 ) {
                    employee.setLocation(cell.getStringCellValue());
                    empList.add(employee);
                    System.out.print(cell.getStringCellValue() + "\t\t");
                }
                }
            System.out.println(""); 


            }


        file.close();       

}catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
    return empList;
}

private static void persistToDB(List<Employee> employees) {
    /*SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    */

        Configuration c = new Configuration();
        c.configure("/hibernate.cfg.xml");
        // SessionFactory holds cfg file properties like // driver props and
        // hibernate props and mapping file
        SessionFactory sf = c.buildSessionFactory();
        // create one session means Connection
        Session s = sf.openSession();
        // before starting save(),update(), delete() operation we need to
        // start TX // starting tx mean con.setAutoCommit(false);
        Transaction tx = s.beginTransaction();
        try {
        for (int i = 0; i < employees.size(); i++) {
            Employee emp = employees.get(i);
            s.save(emp);
        }
        tx.commit();
        s.close();

    } catch (Exception e) {
        tx.rollback();
    }

    }
    }

的hibernate.cfg.xml

    <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>


    <mapping class="test1.Employee"/> 
</session-factory>

</hibernate-configuration>

Employee.java和ReadExcel.java位于src。下的test1包中。

这是我得到的错误

    17:47:44.225 [main] DEBUG o.h.internal.util.EntityPrinter - test1.Employee{id=4,     location=Jayanagara, name=Shwetha}
    17:47:44.234 [main] DEBUG org.hibernate.SQL - 
    insert 
    into
    employee_details
    (location, emp_name, emp_id) 
    values
    (?, ?, ?)
    Hibernate: 
    insert 
    into
    employee_details
    (location, emp_name, emp_id) 
    values
    (?, ?, ?)
    17:47:44.242 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute   statement [n/a]
    org.postgresql.util.PSQLException: ERROR: relation "employee_details" does not     exist
    Position: 13
at    org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)   ~[postgresql-9.1-901.jdbc4.jar:na]
at   org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3067) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3509) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:364) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:356) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:277) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) [hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at test1.ReadExcel.persistToDB(ReadExcel.java:111) [classes/:na]
at test1.ReadExcel.main(ReadExcel.java:27) [classes/:na]
    17:47:44.242 [main] WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0,  SQLState: 42P01
    17:47:44.242 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ERROR: relation    "employee_details" does not exist
    Position: 13

有人可以帮我解决这个问题。我无法弄清楚它为何显示&#34; employee_details&#34;不存在。我在postgres DB的mytestschema中有这个表,它有三列

    emp_id integer not null
    emp_name varchar(255)
    location varchar(255)

3 个答案:

答案 0 :(得分:0)

您的connection.url属性指向'postgres'数据库 - 更改它 jdbc:postgresql://localhost:5432/postgres

jdbc:postgresql://localhost:5432/mytestschema

答案 1 :(得分:0)

您可能需要在 postgres 中创建名称为employee_details的同义词 mytestschema.employee_details的架构,以便可以从 postgres 架构访问该表。

答案 2 :(得分:0)

如果要访问的表位于模式中,则必须通过预先设置schemaname来显式地解决。例如:

@Table(name="employee_details")

如果将其更改为:

,可能会更好地工作
@Table(name="mytestschema.employee_details")

或者,如果您希望postgres用户自动查看非标准模式中的数据,您可以修改postgres设置以在搜索路径中包含模式。

alter role postgres set search_path to public, mytestschema;

一旦输入,每次postgres连接时,将首先在公共模式中查找引用的表/视图/函数,然后查找mytestschema。这样做您不必更改表名以包含模式。

-g