我想把文本字段中的数据插入到数据库中,但我的代码不起作用(虽然控制台中没有错误),我做错了什么?这是一个代码:
Query query = entityManager.createNativeQuery("INSERT INTO Employee(idemployee, name, lastname,"
+ "gender, position, salary, phonenumber, adress) VALUES (:idemployee, :name, :lastname, :gender,"
+ ":position, :salary, :phonenumber, :adress )");
Employee em = new Employee();
em.setEID(emplID.getText());
em.setName(emplName.getText());
em.setLastName(empllastName.getText());
em.setGender(emplGender.getText());
em.setPosition(emplPosition.getText());
em.setSalary(emplSalary.getText());
em.setPhonenumber(emplphoneNumber.getText());
em.setAddress(emplAdress.getText());
query.setParameter("idemployee", em.getEID());
query.setParameter("name", em.getEID());
query.setParameter("lastname", em.getEID());
query.setParameter("gender", em.getEID());
query.setParameter("position", em.getEID());
query.setParameter("salary", em.getEID());
query.setParameter("phonenumber", em.getEID());
query.setParameter("adress", em.getEID());
entityManager.getTransaction().commit();
答案 0 :(得分:1)
未为本机查询定义命名参数的使用。从JPA规范(第3.6.3节命名参数):
命名参数遵循第4.4.1节中定义的标识符规则。命名参数的使用适用于Java Persistence查询语言,并未针对本机查询定义。只有位置参数绑定可以便携地用于本机查询。
请尝试以下方法:
Query query = entityManager.createNativeQuery("INSERT INTO Employee(idemployee, name, lastname,"
+ "gender, position, salary, phonenumber, adress) VALUES (?1, ?2, ?3, ?4,"
+ "?5, ?6, ?7, ?8 )");
Employee em = new Employee();
em.setEID(emplID.getText());
em.setName(emplName.getText());
em.setLastName(empllastName.getText());
em.setGender(emplGender.getText());
em.setPosition(emplPosition.getText());
em.setSalary(emplSalary.getText());
em.setPhonenumber(emplphoneNumber.getText());
em.setAddress(emplAdress.getText());
query.setParameter(1, em.getEID());
query.setParameter(2, em.getEID());
query.setParameter(3, em.getEID());
query.setParameter(4, em.getEID());
query.setParameter(5, em.getEID());
query.setParameter(6, em.getEID());
query.setParameter(7, em.getEID());
query.setParameter(8, em.getEID());
query.setString("status", "purged");
int rowsCopied=query.executeUpdate();
entityManager.getTransaction().commit();
请注意,在JPA> = 2.0中,您可以在本机查询中使用命名参数。
有关详细信息,请按照 JPA/Hibernate Native Queries do not recognize Parameters