我有需要保存在不同购物车中的产品列表。
我需要知道哪些产品已经到达任何购物车,(换句话说,哪些产品在购物车中)我的课程如下,但代码会遇到以下错误。
我以这种方式设计了类,以便能够检索所有具有产品的购物车。 每个产品只能在一个购物车中,因为所有产品的数量总是一个。
购物车类
import javax.persistence.OneToMany;
@Entity
public class Cart{
...
@OneToMany
private List<Product> products = new ArrayList();
...
}
产品
import javax.persistence.ManyToOne;
@Entity
public class Product{
...
@ManyToOne
private Cart cart;
...
}
代码1
Criteria cre = session.createCriteria(Product.class, "pro");
cre.add(Restrictions.eq("pro.status", true))
List<Product> pro = (Product) cre.list();
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'this_.cart_id' in 'field list'
代码2(这是一个单独的代码,不能正常工作并引发类似的错误)
Criteria cre = session.createCriteria(Cart.class, "cart")
.createAlias("cart.products", "pro");
cre.add(Restrictions.isNotEmpty("pro")); //has product
List product = new ArrayList();
product = (List<Product>) cre.list();
SEVERE: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
....
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'pro1_.cart_id' in 'field list'
at sun.reflect.GeneratedConstructorAccessor598.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)