我正在尝试修复由我的数据库上的 Hibernate 查询引起的错误,但我似乎无法找到该查询的来源。在启用sql
log on hibernate 后,我找到了错误所在,但不知道如何修复。
Hibernate query (eclipse log) "update students_classes set student_id=null where student_id=?"
throwing: ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-2) Column 'student_id' cannot be null
错误在这一行抛出:
student = studentDAO.save(student);
保存从何而来
public Entity save(Entity entity) throws Exception {
Entity result = null;
try {
trimAllStrAttributes(entity);
result = em.merge(entity);
} catch (Exception e) {
logger.error("Exception in AbstractDAO", e);
throw e;
}
return result;
}
private void trimAllStrAttributes(Entity product) throws IntrospectionException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
final Class c = product.getClass();
for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(c, Object.class).getPropertyDescriptors()) {
Method method = propertyDescriptor.getReadMethod();
if (method != null) {
String name = method.getName();
// If the current level of Property is of type String
if (method.getReturnType().equals(String.class)) {
String property = (String) method.invoke(product);
if (property != null) {
try {
Method setter = c.getMethod("set" + name.substring(3), new Class<?>[] { String.class });
if (setter != null) {
setter.invoke(product, property.trim());
}
} catch (NoSuchMethodException nsme) {
}
}
}
}
}
}
这可能是一个映射问题,所以这是我的实体:
学生类(class)
@Column(name = "student_id")
private Long studentId;
@Column(name = "classes_id")
private Long classesId;
学生
@AuditJoinTable
@ManyToMany
@JoinTable(name = "students_classes",
joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "classes_id", referencedColumnName = "id"))
private List<Classes> classes;
@NotAudited
@OneToMany
@JoinColumn(name = "student_id")
private List<StudentClasses> studentsClasses;
我该怎么办?改变hibernate的query(去哪里找?)还是mapping层面有问题?
最佳答案
错误会自行解释:
throwing: ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-2) Column 'student_id' cannot be null
根据您的其他映射,我可以肯定地说 studentId 是表的主键,因此,如果您不知道新实体必须具有的 ID,则必须标记该字段以使 hibernate 映射它:
将 studentId 标记为 id
并添加一个自动生成的值:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long studentId;
Hibernate 定义了五种标识符生成策略:
- AUTO - 标识列、序列或表,具体取决于基础数据库
- TABLE - 包含 id 的表
- IDENTITY - 身份列
- SEQUENCE - 序列
- identity copy – 身份是从另一个实体复制的
关于java - 如何查找/更改 hibernate 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206537/