I have a service rest from database generated in netbeans. This creates entity classes for each table .
@Entity
@Table(name = "users")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Users.findAll",
query = "SELECT u FROM Users u"),
@NamedQuery(name = "Users.findById",
query = "SELECT u FROM Users u WHERE u.id = :id"),
@NamedQuery(name = "Users.findByName",
query = "SELECT u FROM Users u WHERE u.name = :name"),
@NamedQuery(name = "Users.findByTelephone",
query = "SELECT u FROM Users u WHERE u.telephone = :telephone"),
@NamedQuery(name = "Users.findByYear",
query = "SELECT u FROM Users u WHERE u.year = :year")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 25)
@Column(name = "name")
private String name;
@Column(name = "telephone")
private Integer telephone;
@Column(name = "year")
private Integer year;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
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 Integer getTelephone() {
return telephone;
}
public void setTelephone(Integer telephone) {
this.telephone = telephone;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@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 Users)) {
return false;
}
Users other = (Users) 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 "glee.Users[ id=" + id + " ]";
}
How I can query the db with this class from another? ?
For example do a select : select name from bb.users;
and save it in an array eg
Thanks
1 Answer 1
@NamedQuery(name,query)annotation is used to hard code the Queries into the Persistence class. You can retrieve thequeryusing thenameattribute specified.When using hibernate session, you can use getNamedQuery to get the query.
When used with EntityManager you can use createNamedQuery.
Both of this will retrieve the query and and you can execute the query with basic query operations.
List Users = session.getNamedQuery("Users.findById").setParameter("id", "1").list();