netbeans中来自数据库的宁静java Web服务

时间:2014-04-23 11:03:39

标签: java web-services rest java-ee netbeans

对不起我的英语,不是很好。

我使用NetBeans创建了一个Restful webservice(从数据库中恢复)。 这将创建实体类和外观(使用其路径,获取等)

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;
}
}

必须进行哪些更改,而不是按ID过滤,放置数据可以报销年份?我解释道。 使用此代码,我在浏览器中写道:

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

它返回一个id为3的xml数据。 好的,基本上我想将我的代码更改为:

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

这将使我的所有用户都回到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 + " ]";
}

}

感谢!

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();
    }

}

3 个答案:

答案 0 :(得分:1)

您应该专注的切入点是

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

您应该将id替换为year并使用抽象超类中的相应方法或使用Users.findByYear查询。

答案 1 :(得分:1)

无法区分../glee.users/3../glee.users/2011 在我看来,你应该在这里使用另一个解决方案:

  • ../glee.users获取所有记录
  • ../glee.users?id=3获取id == 3
  • 的用户
  • ../glee.users?from=2011&to=201320112013之间的所有用户都可以。

要实现此功能,您应该使用@QueryParam注释。

@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();
    }
}

答案 2 :(得分:0)

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