Java使用SQL语句从数据库获取数据

时间:2018-11-19 22:51:56

标签: java sql

所以我的表中有数据,该表在启动时在configbean中初始化。 格式为:字符串ID,字符串名称,双倍率 例如:“ 1”,“阿拉巴马州”,.02

在我的请求bean中,我有一个仅获取名称的函数。

public List<String> getStateNames() {
    List<String> results = em.createNamedQuery("getStateNames").getResultList();
    results.sort(null);
    return results;
}

这是基本文件StateTax

@Entity
@Table(name = "STATE_TAXES")
@NamedQueries({
/*@NamedQuery(
    name = "getTaxRate",
    query = "SELECT t FROM StateTax t WHERE t.stateName = :stateName"),*/
 @NamedQuery(
    name = "getStateNames",
    query = "SELECT t FROM StateTax t ORDER BY t.stateID")
  })
public class StateTax implements Serializable {
@Id
private String stateID;
private String stateName;
private double taxRate;

//supposed to lok like book.java
public StateTax() {

}

public StateTax(String id, String st, double tax) {
    this.stateID = id;
    this.stateName = st;
    this.taxRate = tax;
}

public String getStateID() {
    return stateID;
}

public void setStateID(String stateID) {
    this.stateID = stateID;
}

public String getStateName() {
    return stateName;
}

public void setStateName(String stateName) {
    this.stateName = stateName;
}

public double getTaxRate() {
    return taxRate;
}

public void setTaxRate(double taxRate) {
    this.taxRate = taxRate;
}



public String getState() {
    return stateName;
}

public void setState(String state) {
    this.stateName = state;
}

   @Override
public int hashCode() {
    int hash = 0;
    hash += (stateID != null ? stateID.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    if (!(object instanceof StateTax)) {
        return false;
    }
    StateTax other = (StateTax) object;
    return this.stateID != null || this.stateID == null 
            && other.stateID == null || this.stateID.equals(other.stateID);
}

@Override
public String toString() {
    return "bookstore.entities.StateTax[ stateId=" + stateID + " ]";
}
}

最终产品应该是一个下拉框,允许您在xhtml中选择一个选项。

我的xhtml部分(目前已注释掉):

<h:outputLabel for="stateOption" value="#{bundle.StateName}"/>
            <h:selectOneMenu id="stateName"
                             required="true"
                            valueChangeListener="#{cashierBean.setTax}"> 
                <f:selectItems value="#{cashierBean.stateNames}"
                               var="stateName">                                
                </f:selectItems>
            </h:selectOneMenu>
            <h:message styleClass="error-message" for="stateOption"/>

所以这是我在statetax文件中的SQL语句中得到的部分错误:

Exception Description: Problem compiling [SELECT t FROM StateTax t ORDER BY t.stateId]. 

我的问题:如何从表中正确获取名称列表?

0 个答案:

没有答案