您好我想以JSON格式选择所有数据。我怎么能这样做?
此泛型类包含我用于查找,添加,更新和删除的方法。我应该在selectAll
方法中添加一些东西以使其有效吗?
public class GenericDaoImpl<E> implements IGenericDao<E>{
@PersistenceContext
EntityManager em;
private Class<E> type;
public Class<E> getType() {
return type;
}
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class<E>) pt.getActualTypeArguments()[0];
}
@Override
public E add(E entity) {
em.persist(entity);
return entity;
}
@Override
public E update(E entity) {
return em.merge(entity);
}
@Override
public List<E> selectAll() {
Query query = em.createQuery("select t from " + type.getSimpleName() + " t ");
return (List<E>) query.getResultList();
}
@Override
public List<E> selectAll(String sortField, String sort) {
Query query = em.createQuery("select t from"+type.getSimpleName()+ " t order by " + sortField + " " + sort);
return query.getResultList();
}
@Override
public E getById(Long id) {
return em.find(type, id);
}
@Override
public void remove(Long id) {
E tab = em.getReference(type, id);
em.remove(tab);
}
@Override
public E findOne(String paramName, Object paramValue) {
Query query = em.createQuery("select t from"+type.getSimpleName()+ " t where " + paramName + " = :x");
query.setParameter(paramName, paramValue);
return query.getResultList().size()>0 ? (E) query.getResultList().get(0):null;
}
@Override
public E findOne(String[] paramName, Object[] paramValue) {
if (paramName.length != paramValue.length) {
return null;
}
String queryString = "select e from " + type.getSimpleName() + " e where ";
int len = paramName.length;
for (int i = 0; i < len; i++) {
queryString += " e." + paramName[i] + "= :x" + i;
if ((i + 1) < len) {
queryString += " and ";
}
}
Query query = em.createQuery(queryString);
for (int i = 0; i < paramValue.length; i++) {
query.setParameter("x" + i, paramValue[i]);
}
return query.getResultList().size() > 0 ? (E) query.getResultList().get(0) : null;
}
@Override
public int findCountBy(String paramName, Object paramValue) {
Query query = em.createQuery("select t from"+type.getSimpleName()+ " t where " + paramName + " = :x");
query.setParameter(paramName, paramValue);
return query.getResultList().size() > 0 ?((Long)query.getSingleResult()).intValue():0;
}
@Override
public E getByLogin(String login) {
return em.find(type, login);
}
@Override
public E getByIdAdmin(Integer id) {
return em.find(type, id);
}
@Override
public void removeByLogin(String login) {
E tab = em.getReference(type, login);
em.remove(tab);
}
@Override
public void removeByIdAdmin(Integer id) {
E tab = em.getReference(type, id);
em.remove(tab);
}
}