Id suggest creating a POJO that can be mapped to your table you're retrieving values from:
@Entity
@Table(name = "MyTable")
@NamedQueries({
@NamedQuery(name = "MyTable.findAll", query = "SELECT m FROM MyTable m")})
public class MyTable implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@Basic(optional = false)
@Column(name = "display_name")
private String displayName;
public MyTable() {
}
public MyTable(Integer id) {
this.id = id;
}
public MyTable(Integer id, String name, String displayName) {
this.id = id;
this.name = name;
this.displayName = displayName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MyTable)) {
return false;
}
MyTable other = (MyTable ) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "MyTable[ id=" + id + " ]";
}
}
Obviously fill in the fields as you need with the corresponding database datatype repersentation.
Notice how i have NamedQueries
we can now take advantage of those named queries to do our fetches
TypedQuery<MyTable> query = entityManager.createNamedQuery("MyTable.findAll", MyTable.class);
List<MyTable> results = query.getResultList();
this will do all the casting and conversions for you. You can add all the named queries you want.
https://www.objectdb.com/java/jpa/query/named
UPDATE
If you need to dynamically create a query you can do the following:
String query = "SELECT m FROM MyTable m Where m.id =:id and m.name=:name";
///modify the query as needed based off of other conditions)
TypedQuery<MyTable > query = em.createQuery(query, MyTable .class);
query.setParameter("id", id);
query.setParameter("name", name);
List<MyTable> results = query.getResultList();
https://www.objectdb.com/java/jpa/query/api