为什么Hibernate检测到空值? (使用session.save())

时间:2016-10-20 06:10:55

标签: java hibernate

我正在通过Hibernate的session.save(object)保存一个对象,但它获取一个空值。我尝试打印值,它不是空的。这是我的疑问:

@Override
public void addProductInCart(CartProduct product) {

    System.out.println(product.getProduct().getUpc() + " " + product.getUserId() + " " + product.getQuantity());

    Session session = sessionFactory.openSession();

    Transaction transaction = null;

    try {
        transaction = session.beginTransaction();

        session.save(product);

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

印刷品的输出是:

765571624769 1 1

这意味着值已存在,但我收到此错误:

Oct 20, 2016 2:02:45 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1048, SQLState: 23000
Oct 20, 2016 2:02:45 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Column 'upc' 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.CartDaoHQLImpl.addProductInCart(CartDaoHQLImpl.java:103)
at com.qbryx.service.CustomerServiceImpl.addProductInCart(CustomerServiceImpl.java:67)
at com.qbryx.controller.CustomerController.productCart(CustomerController.java:91)
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 'upc' 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

这是CartProduct对象:

@Entity
@Table(name = "CART")
public class CartProduct {

private long id; 

private long userId;

private Product product;

private int quantity;

private int isPurchased;

public CartProduct(){}

public CartProduct(long id, long userId, Product product, int quantity, int isPurchased) {
    super();
    this.id = id;
    this.userId = userId;
    this.product = product;
    this.quantity = quantity;
    this.isPurchased = isPurchased;
}

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

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

@Column(name = "user_id")
public long getUserId() {
    return userId;
}

public void setUserId(long userId) {
    this.userId = userId;
}

@OneToOne
@JoinColumn(name="upc", referencedColumnName = "upc")
public Product getProduct() {
    return product;
}

public void setProduct(Product product) {
    this.product = product;
}

@Column(name = "quantity")
public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

@Column(name = "is_purchased")
public int isPurchased() {
    return isPurchased;
}

public void setPurchased(int isPurchased) {
    this.isPurchased = isPurchased;
}

@Transient
public BigDecimal totalPrice(){
    BigDecimal totalPrice = BigDecimal.ZERO;

    totalPrice = getProduct().getPrice().multiply(new BigDecimal(getQuantity()));

    return totalPrice;
}

@Override
public String toString() {
    return "CartProduct [id=" + id + ", userId=" + userId + ", product=" + product + ", quantity=" + quantity
            + ", isPurchased=" + isPurchased + "]";
}
}

这是我的产品类:

@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")
public String getUpc() {
    return upc;
}

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

@OneToOne
@JoinColumn(name = "category_id", referencedColumnName = "category_id", insertable = false, updatable = false)
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;
}
}

1 个答案:

答案 0 :(得分:0)

我把注释放在字段级别,我也建议如果不给你带来麻烦,也要改变你的类并将注释放在字段级别,因为我看到了奇怪的东西,取决于休眠将注释放在访问(gettter)级别时的版本。

尝试更改产品类,如:

public class Product implements java.io.Serializable {
.....
    @OneToOne
    @JoinColumn (name="cartProduct")
    private CartProduct cartProduct;
.....
}

购物车产品:

public class CartProduct implements java.io.Serializable {
.....
 @OneToOne (mappedBy="cartProduct")
 private Product product;
.....
}

同样适用于该领域:

@OneToOne
@JoinColumn(name = "category_id", referencedColumnName = "category_id", insertable = false, updatable = false)
public Category getCategory() {
    return category;
}

我认为您还必须更改此@OneToOne,但不确定,因为您尚未发布Category课程。

此外,如果这样可以解决您的问题,那么当您要插入/更新或删除@OneToOne映射的实体时,您必须关心级联模式。 有关详情,请查看此tutorial或此one