我无法从组合键检索确切的 ID。
我正在使用 MySQL 和 Hibernate。
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(ProductId.class);
criteria.setProjection(Projections.max("id"));
criteria.setMaxResults(1);
Integer max = (Integer) criteria.uniqueResult();
if (max == null) {
max = 0;
//This always giving null.
所以它max =0;
插入之前或之后数据库没有问题。
但是使用以下方式检索id
:
productId.getId();
也始终给出零,但在数据库中它会递增 id
。
为什么会这样?
它一定不会导致它有值(value):
ProductId productId = new ProductId(id, barcode);
product.setName(name);
product.setPrice(price);
product.setId(productId);
id
是主键、自动递增和< em>唯一,但条形码
只是主键。
这两个字段都是复合键。
夏天:
当我跳过启动 id 时,它给出
java.lang.NullPointerException
因此,如果它被初始化,它可以在插入时自动生成id,即使只是输入“0”
ProductId productId = new ProductId(0, barcode);
完成插入。
但我无法检索准确的id
。
我正在使用以下方式保存产品:
String name = jNameTextField.getText();
double price = Double.parseDouble(jPriceTextField.getText());
int barcode = Integer.parseInt(jBarcdTextField.getText());
ProductId productId = new ProductId(0, barcode); // put zero for check
product.setName(name);
product.setPrice(price);
product.setId(productId);
manager.addProduct(product);
产品.java
public class Product implements java.io.Serializable {
public ProductId id;
private String name;
private double price;
private Stock stock;
public Product() {
}
public Product(ProductId id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public Product(ProductId id, String name, double price, Stock stock) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
// Getter and Setters
谢谢。
最佳答案
我仍然建议删除 ProductId 类,因为它的 id 值是唯一的。 但是,要使查询与 ProductId 类一起使用:
Criteria criteria = session.createCriteria(Product.class);
将条件更改为 Product 类而不是 ProductId 类。
我认为(但我不确定)下面的更改也是必要的,将 Hibernate 指向 ProductId id 字段的 int id 字段。
criteria.setProjection(Projections.max("id.id"));
我还建议更改两个 id 字段之一的名称,以使代码不那么困惑。
关于java - 无法从组合键检索准确的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904794/