Question

Model class

    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;
}
    }

Main Class

    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 and ReadExcel.java are located in test1 package under src.

This is the error that i am getting

    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

Can someone please help me with this.I am not able to figure out why it is showing "employee_details" does not exist. i have this table in mytestschema in postgres DB and it has three columns

    emp_id integer not null
    emp_name varchar(255)
    location varchar(255)
Was it helpful?

Solution

If the table you want to access is in a schema, you have to explicitly address is by prepending the schemaname. For example:

@Table(name="employee_details")

Might work better if you change it to:

@Table(name="mytestschema.employee_details")

Or, if you want the postgres user to automatically see data in non standard schemas you can modify the postgres settings to include the schema in the search path.

alter role postgres set search_path to public, mytestschema;

Once entered, every time postgres connects the tables/views/functions that are referenced will be looked for in the public schema first, then the mytestschema. Doing it this way you don't have to change the table name to include the schema first.

-g

OTHER TIPS

Your connection.url property is pointing to the 'postgres' database - Change it from jdbc:postgresql://localhost:5432/postgres

to

jdbc:postgresql://localhost:5432/mytestschema

You might have to create a synonym with name employee_details in the postgres schema for mytestschema.employee_details so that the table can be accessed from the postgres schema.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top