美好的一天。我尝试使用CriteriaQuery从表中选择行。
我有一个对象Card
:
@Entity(name = "bank_cards")
public class Card {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToMany(mappedBy = "cards")
private Set<Account> accounts;
private String number;
private float amount;
private String expire;
private String type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getExpire() {
return expire;
}
public void setExpire(String expire) {
this.expire = expire;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Set<Account> getAccounts() {
return accounts;
}
public void setAccounts(Set<Account> accounts) {
this.accounts = accounts;
}
}
使用CriteriaQuery选择行:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("cards");
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Card> cq = cb.createQuery(Card.class);
Metamodel m = em.getMetamodel();
EntityType<Card> Card_ = m.entity(Card.class);
Root<Card> card = cq.from(Card.class);
cq.where(card.get(Card_.number)); // error
找不到最后一个字符串字段number
。
persistence.xml中的链接单元:
<persistence-unit name="users" transaction-type="RESOURCE_LOCAL">
<class>main.java.entities.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/java" />
<property name="javax.persistence.jdbc.user" value="java" />
<property name="javax.persistence.jdbc.password" value="java" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
我需要执行下一个查询:
"SELECT * FROM bank_cards WHERE number='" + cardNumber + "'"
cardNumber - string
元模型课程:
@StaticMetamodel(Card.class)
public class Card_ {
public static volatile SingularAttribute<Card, Integer> id;
public static volatile SingularAttribute<Card, String> number;
public static volatile SingularAttribute<Card, String> expire;
public static volatile SingularAttribute<Card, String> type;
public static volatile SingularAttribute<Card, Float> amount;
public static volatile SetAttribute<Card, Account> accounts;
}
答案 0 :(得分:1)
你的谓词错了。
public Card byNumber(String number) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Card> cq = cb.createQuery(Card.class);
Root<Card> card = cq.from(Card.class);
Predicate equalPredicate = cb.equal(card.get(Card_.number), number);
cq.where(equalPredicate);
cq.select(card);
return em.createQuery(cq).getSingleResult();
}