我正在使用 Eclipse Juno IDE。
我有一个客户端-服务器应用程序。在服务器端,我有一个实体(旅行),我有另一个处理 JPA 查询的类。我正在从数据库中接收数据,但是当我尝试将其作为向量发送给客户端时,我在客户端遇到了一个异常,上面写着“Cant cast pack.db.Travels to java.util.向量”
这是我的代码: 实体:
package pack.db;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Travels implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@Column(name="id")
private int id;
@Column(name="taxi_number")
private String taxiNumber;
@Column(name="travel_date")
private Date travelDate;
@Column(name="travel_time")
private Time travelTime;
@Column(name="cost")
private Double travelCost;
public Travels() {
super();
}
public void setNumber(String number)
{
this.taxiNumber = number;
}
public void setDate(Date date)
{
this.travelDate = date;
}
public void setTime(Time time)
{
this.travelTime = time;
}
public void setCost(Double cost)
{
this.travelCost = cost;
}
}
查询类
public Vector retrieveAllTravelsData(Date[] travelDate, Time[] travelTime) {
List<Object[]> allTravels = (List<Object[]>)em.createQuery("SELECT t FROM Travels t WHERE t.travelDate between ?1 and ?2 and " +
"t.travelTime between ?3 and ?4")
.setParameter(1, travelDate[0])
.setParameter(2, travelDate[1])
.setParameter(3, travelTime[0])
.setParameter(4, travelTime[1]).getResultList();
return (Vector) allTravels;
}
所以我想做的是将“allTravels”作为向量发送到客户端,因为我需要在客户端填充一个 JTABLE。所以我尝试将查询中的返回数据转换为 OBJECT[] (因为 JTABLE 的构造函数需要 Object[][] 的行)并发送它..但我仍然在客户端遇到异常说“无法将 pack.db.Travel 转换为 java.util.Vector”.. 我认为我不需要在客户端添加 travel Entity.. 那么如何将数据发送到客户端?
更具体地说..我有这个带有JDBC实现的代码
public Vector retrieveAllTravelsData(Date[] travelDate, Time[] travelTime) {
Vector rows_data = new Vector();
String sql = "SELECT * FROM taxis.travels " + " WHERE travel_date BETWEEN ? AND ? AND travel_time BETWEEN ? AND ?";
try {
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setDate(1, travelDate[0]);
statement.setDate(2, travelDate[1]);
statement.setTime(3, travelTime[0]);
statement.setTime(4, travelTime[1]);
rs = statement.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
int cols_count = meta.getColumnCount();
while (rs.next()) {
Vector record = new Vector();
for (int i = 0; i < cols_count; i++) {
record.add(rs.getString(i+1));
}
rows_data.addElement(record);
}
} catch (SQLException e) {
while (e != null) {
e.printStackTrace();
e = e.getNextException();
}
}
return rows_data;
在这里,我可以从每一列中获取每一列数据,将其保存为记录,然后将其放入 Vector 中。那么JPA如何实现呢?可能吗?