如何使用java在postgres数据库中插入数据?这是我正在执行的代码,它会抛出一个错误:
public static Result add() {
response().setContentType("application/json");
JsonNode val = request().body().asJson();
System.out.println(val);
ObjectNode result= new ObjectNode(val);
String firstname=val.findPath("firstname").textValue();
System.out.println(firstname);
String lastname=val.findPath("lastname").textValue();
System.out.println(lastname);
result.put(firstname, 1);
result.put(lastname, 2);
System.out.println(result);
Ebean.save(result);
return ok(index.render("Record has been inserted"+user));
}
答案 0 :(得分:0)
Play使用Ebean(默认情况下)作为使用JPA映射实体的持久性框架。有关详情,请参阅docs。 因此,您只能持久保存JPA带注释的实体。您正在尝试保留Jackson ObjectNode对象,该对象显然不是JPA带注释的实体。
假设您要保留的是Person,您的代码将更改为以下内容:
应用程序/模型/ Person.java
package models;
import play.db.ebean.Model;
import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Id;
@Entity
public class Person extends Model {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "person_seq_gen")
@SequenceGenerator(name = "person_seq_gen", sequenceName = "person_id_seq")
public Long id;
public String firstName;
public String lastName;
}
在您的控制器类中:
public static Result add() {
JsonNode val = request().body().asJson();
System.out.println(val);
String firstname=val.findPath("firstname").textValue();
System.out.println(firstname);
String lastname=val.findPath("lastname").textValue();
System.out.println(lastname);
Person person = new Person();
person.firstName = firstname;
person.lastName = lastname;
person.save();
return ok(index.render("Record has been inserted"+person));
}
注意您还必须为Postgres配置jdbc驱动程序。 See here
此代码将保留您的" person"记录在一个名为“人物”的表中。
答案 1 :(得分:0)
public static Result add() throws Exception {
Myapps user = new Myapps();
try {
JsonNode requestBody = request().body().asJson();
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(user);
user = reader.readValue(requestBody);
user.save();
} catch (Exception e) {
e.printStackTrace();
}
return ok(Json.toJson("inserted value is" + user));
}