gpt4 book ai didi

java - 为什么我得到一个空值? ( hibernate , Spring )

转载 作者:行者123 更新时间:2023-11-30 07:58:45 25 4
gpt4 key购买 nike

当我尝试添加新对象时,为什么 Hibernate 会检测到空值?我有一个具有字段对象类别的产品类。 Product 中的类别作为 category_id 存储在数据库中。这是我的产品类。

@Entity
@Table(name = "PRODUCT")
public class Product implements java.io.Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

private long id;

private String upc;

private Category category;

private String name;

private String description;

private BigDecimal price;

public Product(){

}

public Product(String upc){
this.upc = upc;
}

public Product(String upc, String name, BigDecimal price){
this.upc = upc;
this.name = name;
this.price = price;
}

public Product(String upc, Category category, String name, String description, BigDecimal price) {
super();
this.upc = upc;
this.category = category;
this.name = name;
this.description = description;
this.price = price;
}

public void setId(long id) {
this.id = id;
}

@Id @GeneratedValue
@Column(name = "id")
public long getId() {
return id;
}

@Column(name = "upc", nullable = false)
public String getUpc() {
return upc;
}

public void setUpc(String upc) {
this.upc = upc;
}

@ManyToOne @NotNull
@JoinColumn(name = "category_id", referencedColumnName = "category_id")
public Category getCategory() {
return category;
}

public void setCategory(Category category) {
this.category = category;
}

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Column(name = "description")
public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

@Column(name = "price")
public BigDecimal getPrice() {
return price;
}

public void setPrice(BigDecimal price) {
this.price = price;
}
}

这是我的类别类:

@Entity
@Table(name = "CATEGORY")
public class Category implements Serializable{

/**
*
*/
private static final long serialVersionUID = 1L;

private long id;
private String categoryId;
private String name;
private Set<Product> products;

public Category(){}

public Category(String categoryId, String name) {
super();
this.categoryId = categoryId;
this.name = name;
}

public void setId(long id) {
this.id = id;
}

@Id @GeneratedValue
@Column(name = "id")
public long getId() {
return id;
}

@Column(name = "category_id")
public String getCategoryId() {
return categoryId;
}

public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@OneToMany
@JoinColumn(name = "category_id", insertable = false, updatable = false)
public Set<Product> getProducts() {
return products;
}

public void setProducts(Set<Product> products) {
this.products = products;
}
}

现在,当我使用 session.save(product) 方法时,它会为 Category 字段获取一个空值,但在使用 native sql 时运行完美。我试图打印类别 ID 及其位置。这是我添加产品的代码:

@Override
public void addProduct(Product product) {

System.out.println(product.getCategory().getCategoryId());

Session session = sessionFactory.openSession();

Transaction transaction = null;

try {
transaction = session.beginTransaction();

// Query query = session.createSQLQuery(DAOQuery.HQL_ADD_PRODUCT).setParameter("upc", product.getUpc())
// .setParameter("category", product.getCategory().getCategoryId())
// .setParameter("name", product.getName()).setParameter("description", product.getDescription())
// .setParameter("price", product.getPrice());
//
// query.executeUpdate();
session.save(product);

transaction.commit();
} catch (HibernateException e) {
if (transaction != null)
transaction.rollback();

e.printStackTrace();
} finally {
session.close();
}
}

这里是错误:

WARN: SQL Error: 1048, SQLState: 23000
Oct 20, 2016 8:30:15 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Column 'category_id' cannot be null
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2840)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3411)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:597)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:232)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:213)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:256)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:667)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:659)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:654)
at com.qbryx.dao.ProductDaoHQLImpl.addProduct(ProductDaoHQLImpl.java:138)
at com.qbryx.service.ManagerServiceImpl.addProduct(ManagerServiceImpl.java:24)
at com.qbryx.controller.ManagementController.createProduct(ManagementController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:180)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.orm.hibernate5.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: Column 'category_id' cannot be null
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1129)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:681)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1368)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1283)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1268)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 63 more

我似乎找不到问题所在。我需要帮助。谢谢。

最佳答案

错误表明 categoryId 为空,而您的数据库配置为不为空。

你用 @Id @GeneratedValue 标记了 id 并且 Hibernate 为它生成了一个新的 long 值,但是如果你不为 categoryId 提供一个值它就不会生成。

您应该将 @Id @GeneratedValue 移动到 categoryId 或在构建它时提供一个值。

此外,我建议您检查一下您的设计,因为在您的类中同时拥有 idcategoryId 会造成混淆;最终,每个人​​都会将属性 id 称为“category id”,而您不知道他们指的是该 id 还是“categoryId”。

关于java - 为什么我得到一个空值? ( hibernate , Spring ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40154782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com