Emmanuelguther
Emmanuelguther

Reputation: 1059

Restful java Web service from database in netbeans

Sorry for my English, is not very good.

I created a Restful webservice with NetBeans (restful from database). This creates the entity classes and the facade (with its path, get etc)

UsersFacadeRest.java

@Stateless
@Path("glee.users")
public class UsersFacadeREST extends AbstractFacade<Users> {
@PersistenceContext(unitName = "WebApplication6PU")
private EntityManager em;

public UsersFacadeREST() {
    super(Users.class);
}

@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Users entity) {
    super.create(entity);
}
@PUT
@Path("{id}")
@Consumes({"application/xml", "application/json"})
public void edit(@PathParam("id") Integer id, Users entity) {
    super.edit(entity);
}
@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
    super.remove(super.find(id));
}

@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Users find(@PathParam("id") Integer id) {
    return super.find(id);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Users> findAll() {
    return super.findAll();
}
@GET
@Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<Users> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
    return super.findRange(new int[]{from, to});
}

@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
    return String.valueOf(super.count());
}
@Override
protected EntityManager getEntityManager() {
    return em;
}
}

What changes would have to do so that instead of filtering by id, putting data could reimburse the year? I explained. With this code I write in the browser:

 http://localhost:8080/WebApplication6/webresources/glee.users/3 

And it returns an xml data with id 3. Ok, basically I want to change my code to:

 http://localhost:8080/WebApplication6/webresources/glee.users/2011 (filter by year     
 2011)

and this returns me all users with 2011.

Users.java

@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 + " ]";
}

}

THANKS !

abstractFacade

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

Upvotes: 0

Views: 4105

Answers (3)

learner
learner

Reputation: 3110

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
@Path("/YOUR_PATH")
public Service postService(@FormParam("EMP_ID") String param1)
{
    //Do your stuff
}

Upvotes: 0

Ilya
Ilya

Reputation: 29693

It's impossible to distinguish ../glee.users/3 and ../glee.users/2011.
In my opinion, you should use another solution here:

  • ../glee.users to get all record
  • ../glee.users?id=3 to get user with id == 3
  • ../glee.users?from=2011&to=2013 to get all users between 2011 and 2013.

To implement this, you should use @QueryParam annotation.

@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Users> find(@QueryParam("id")   Integer id,
                        @QueryParam("from") Integer from,
                        @QueryParam("to")   Integer to) 
{
    // ... e.g.
    if (id != null)
    {
       return super.find(id);
    }
    else if (from != null || to != null)
    {
       return super.findRange(new int[]{from, to});
    }
    else
    {
       return super.findAll();
    }
}

Upvotes: 1

Smutje
Smutje

Reputation: 18143

The entry point you should concentrate on is

@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Users find(@PathParam("id") Integer id) {
    return super.find(id);
}

where you should replace id with year and use the corresponding method from your abstract super class or use the Users.findByYear query.

Upvotes: 1

Related Questions