Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在读取excel文件后,我试图将数据保存在postgres表中。在尝试提交时,我收到一个强制转换错误_Java_Excel_Hibernate_Postgresql - Fatal编程技术网

Java 在读取excel文件后,我试图将数据保存在postgres表中。在尝试提交时,我收到一个强制转换错误

Java 在读取excel文件后,我试图将数据保存在postgres表中。在尝试提交时,我收到一个强制转换错误,java,excel,hibernate,postgresql,Java,Excel,Hibernate,Postgresql,模范班 package test1; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="employee_details") public class Employee { @Id private String emp_id; private String e

模范班

    package test1;

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

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

public String getEmp_id() {
    return emp_id;
}
public void setEmp_id(String emp_id) {
    this.emp_id = emp_id;
}
public String getEmp_name() {
    return emp_name;
}
public void setEmp_name(String emp_name) {
    this.emp_name = emp_name;
}
public String getLocation() {
    return location;
}
public void setLocation(String location) {
    this.location = location;
}



    }
数据库表脚本

    CREATE TABLE mytestschema.employee_details
    (
    emp_id character varying(255),
    emp_naame character varying(255),
    location character varying(255)
    )
    WITH (
    OIDS=FALSE
    );
    ALTER TABLE mytestschema.employee_details
    OWNER TO postgres;
休眠cfg文件

    <?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>

列“emp_id”不是表中的整数类型,但我无法找出出现此错误的原因。请有人帮忙。

我建议使用数字作为id列(在Employee类中,您当前拥有私有字符串emp_id;将其替换为私有int emp_id;或私有long emp_id;并相应地更改其余代码,可能会消除错误并使代码更简洁)@Kristjan我尝试使用数字列作为emp_id。但是,正如您一定注意到的,我首先将值存储在一个字符串列表中。我将列表的类型更改为Object,将变量的类型更改为int。但是在尝试将emp_id的值保存在变量中时,我得到了一个Numberformat异常:java、 lang.NumberFormatException:对于输入字符串:“1.0”。我使用了Integer.parseInt(string s)方法。我想您可以使用int id=(int)Double.parseDouble(“1.0”);@Kristjan非常感谢:)。它工作得很好。
    package test1;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;

    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;

    public class test2 {
static List<Employee> empList = new ArrayList<Employee>();
static List<String> valueHolder = new ArrayList<String>();
public static void main(String[] args) {

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

private static List<Employee> readExcel(String filepath) {
    try {
        FileInputStream file = new FileInputStream(new   File("D:\\test.xls"));
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {

            Row row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                valueHolder.add(cell.toString());

            }

        }
        for(int i = 0; i < valueHolder.size(); i+=3){
            String first = valueHolder.get(i);
            String second = null;
            String third = null;
            if(valueHolder.size() > i + 2){
            second = valueHolder.get(i + 1);
            third = valueHolder.get(i+2);

            System.out.println("First [" + first + "] - Second [" + second   + "] - Third [" +third +"]");
            Employee employee = new Employee();
            employee.setEmp_id(first);
            employee.setEmp_name(second);
            employee.setLocation(third);
            empList.add(employee);

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

}




@SuppressWarnings("deprecation")
private static void persistToDB(List<Employee> employees) {
    Configuration c = new Configuration();
    c.configure("/hibernate.cfg.xml");
    SessionFactory sf = c.buildSessionFactory();
    Session s = sf.openSession();
    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();
    }

}
    }
    14:19:17.114 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute   statement [n/a]
    org.postgresql.util.PSQLException: ERROR: column "emp_id" is of type integer but  expression is of type character varying
    Hint: You will need to rewrite or cast the expression.
    Position: 75
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:38 8) ~[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.test2.persistToDB(test2.java:87) [classes/:na]
at test1.test2.main(test2.java:28) [classes/:na]
    14:19:17.114 [main] WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0,  SQLState: 42804
    14:19:17.114 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ERROR: column   "emp_id" is of type integer but expression is of type character varying
    Hint: You will need to rewrite or cast the expression.
    Position: 75
    14:19:17.115 [main] DEBUG o.h.e.t.spi.AbstractTransactionImpl - rolling back
    14:19:17.116 [main] DEBUG o.h.e.t.i.jdbc.JdbcTransaction - rolled JDBC Connection