我有一个像这样的对象MyObject:
@Entity
@Table(name = "mytable")
public class MyObject{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name="title")
private String title;
@Column(name="users")//, columnDefinition="bigint[]")
@ElementCollection
private List<Long> users = new ArrayList<>();
//constructor, getters and setters
}
使用DAO MyObjectDAO.class(其中定义了创建方法)(create(MyObject mo)),以及资源类MyObjectResource,其内容为:
@POST
@UnitOfWork
public Response createMyObject(MyObject mo) {
Response resp;
try {
MyObject mo0 = MyObjectDAO.create(mo);
if(mo0!=null) {
resp = Response.status(Response.Status.OK).entity(mo0).build();
}
else {
resp = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("MyObjectnull, can't be created in database").build();
}
}
catch(Exception e) {
resp = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("MyObjectnull, can't be created in database\n"+e.getMessage()).build();
}
return resp;
}
当我尝试使用POST创建MyObject时,例如{“ id”:0,“ title”:“ dyud u”,“ users”:[334,335]},我收到错误消息:
org.hibernate.engine.jdbc.spi.SqlExceptionHelper:SQL错误:0, SQLState:42804错误 [org.hibernate.engine.jdbc.spi.SqlExceptionHelper:ERREUR:la Colonne «用户»键入bigint []表示键入bigint
当用户为null或空或使用sql命令手动创建时,我没有问题创建:
INSERT INTO mytable ("title","users") VALUES ('t1','{334,335}');
我该怎么办?
答案 0 :(得分:2)
将this dependency添加到您的项目中,并将字段更改为:
@Column(name="users", columnDefinition="bigint array")
private Long[] users;
这将适用于6.0之前的Hibernate 5.2+版本,然后需要更新该库。
答案 1 :(得分:0)
否则,没有这种依赖关系就可以工作:
@Entity
@Table(name="mytable")
@NamedQueries({
@NamedQuery(name="findAll",query = "SELECT n FROM mytable n"),
@NamedQuery(name="getForUser", query = "SELECT n FROM mytable n WHERE :user MEMBER OF n.users")
})
public class MyObject{
@Id
@GeneratedValue(startegy = GenerationType.IDENTITY)
private long id;
@Column(name="title")
private String title;
@ElementCollection
private Set<Long> users = new HashSet<>();
//constructor, getters and setters
}
它添加一个表myobject_users,其中有myobject_id和users列。创建新的MyObject没有问题。