private static void pecas() { Session session = HibernateUtil.getSession(); session.beginTransaction(); for (String linha : getPecasFromCSV()) { String[] item = linha.split(";"); String hqlMarca = "from Marca m where m.nome = :nome "; Query queryMarca = session.createQuery(hqlMarca).setString("nome", item[2]); Marca marca = (Marca) queryMarca.uniqueResult(); if (marca == null || marca.getId() == 0) { marca = new Marca(); marca.setNome(item[2]); session.saveOrUpdate(marca); } Peca peca = new Peca(); peca.setNome(item[0]); peca.setDescricao(item[1] + " - " + item[3]); peca.setQuantidade(50); peca.setMarca(marca); session.saveOrUpdate(peca); TarifarioPeca tarifarioPeca = new TarifarioPeca(); tarifarioPeca.setData(new Date()); tarifarioPeca.setValor(Double.parseDouble(item[4])); tarifarioPeca.setMarkup(25); tarifarioPeca.setValorVenda( (tarifarioPeca.getValor() * (25 / 100)) + tarifarioPeca.getValor()); tarifarioPeca.setPeca(peca); session.saveOrUpdate(tarifarioPeca); String hqlTipoServico = "from TipoServico m where m.nome = :nome "; Query queryTipoServico = session.createQuery(hqlTipoServico).setString("nome", "Troca de peça"); TipoServico tipoServico = (TipoServico) queryTipoServico.uniqueResult(); if (tipoServico == null || tipoServico.getId() == 0) { tipoServico = new TipoServico(); tipoServico.setNome("Troca de peça"); session.saveOrUpdate(tipoServico); } Servico servico = new Servico(); servico.setNome(item[5]); servico.setDescricao(item[5]); servico.setTipoServico(tipoServico); session.saveOrUpdate(servico); TarifarioServico tarifarioServico = new TarifarioServico(); tarifarioServico.setData(new Date()); tarifarioServico.setServico(servico); tarifarioServico.setValor(Double.parseDouble(item[6])); session.saveOrUpdate(tarifarioServico); } session.getTransaction().commit(); System.out.println("Peças importadas!"); }
private static boolean atualizarCarencia(Segurado segurado, Long idTitular) throws Exception { String sqlConsignacao = "select min(c.dataDoCredito) from ConsignacaoSegurado c where c.titular.idSegurado = :idTitular " + "and c.statusConsignacao = 'P' and c.dataDoCredito >= :dataAdesao"; String sqlCobranca = "select min(c.dataPagamento) from Cobranca c where c.titular.idSegurado = :idTitular " + "and descricao = 'Pago(a)' and c.dataPagamento >= :dataAdesao"; Query queryConsignacao = HibernateUtil.currentSession().createQuery(sqlConsignacao); Query queryCobranca = HibernateUtil.currentSession().createQuery(sqlCobranca); queryConsignacao.setLong("idTitular", idTitular); queryConsignacao.setDate("dataAdesao", segurado.getDataAdesao()); Date inicioCarencia = (Date) queryConsignacao.uniqueResult(); if (inicioCarencia == null) { queryCobranca.setLong("idTitular", idTitular); queryCobranca.setDate("dataAdesao", segurado.getDataAdesao()); inicioCarencia = (Date) queryCobranca.uniqueResult(); } if (inicioCarencia != null) { System.out.println(segurado.getNumeroDoCartao() + " - " + inicioCarencia); segurado.setInicioDaCarencia(inicioCarencia); ImplDAO.save(segurado); return true; } return false; }
@Test public void basicCRUD() { try { Actor actor = new Actor(); actor.setFirstName("Arnold"); actor.setLastName("Schwarzenegger"); actor.setNickName("Arnie"); Date date1 = new SimpleDateFormat("MM/dd/yy").parse("06/30/47"); actor.setBirthDate(date1); getSession().save(actor); Query query = getSession().createQuery("from Actor where nickname=:nickname"); query.setParameter("nickname", "Arnie"); Actor arnie = (Actor) query.uniqueResult(); assertEquals(2, arnie.getId()); arnie.setNickName("Big Guy"); getSession().save(arnie); query.setParameter("nickname", "Big Guy"); Actor arnie2 = (Actor) query.uniqueResult(); assertEquals("Version should match", 1, arnie2.getVersion()); getSession().delete(actor); Actor arnie3 = (Actor) query.uniqueResult(); assertEquals("Arnie should no longer exist!", null, arnie3); } catch (Exception ex) { logger.error("Excption thrown: ", ex.getMessage()); assertTrue(ex.getMessage(), false); ex.printStackTrace(); } }
@Test public void test() { String username = "******"; String password = "******"; String hqlSame = " from User u where u.username = '******' "; Query query = session.createQuery(hqlSame); User user = (User) query.uniqueResult(); if (user == null) { String hqlId = " select u.userId from User u where u.userId >=ALL(select u.userId from u)"; Query queryId = session.createQuery(hqlId); int id = (int) queryId.uniqueResult(); id++; Transaction transaction = (Transaction) session.beginTransaction(); session.save(new User(id, username, password, username + "_" + password, 0)); Userditals ud = new Userditals(); ud.setUser(user); ud.setUserId(id); ud.setRegdate(new Timestamp(System.currentTimeMillis())); session.save(ud); transaction.commit(); } else { System.out.println("Óû§ÃûÖظ´£¡"); } }
public FacturaAlmacen cierra(FacturaAlmacen factura, Usuario usuario) throws NoSePuedeCerrarException, NoSePuedeCerrarEnCeroException, NoEstaAbiertaException { if (factura != null) { if (factura.getEstatus().getNombre().equals(Constantes.ABIERTA)) { if (usuario != null) { factura.setAlmacen(usuario.getAlmacen()); } Date fecha = new Date(); factura.setIva(BigDecimal.ZERO); factura.setTotal(BigDecimal.ZERO); Query query = currentSession().createQuery("select e from Estatus e where e.nombre = :nombre"); query.setString("nombre", Constantes.FACTURADA); Estatus facturada = (Estatus) query.uniqueResult(); for (Salida salida : factura.getSalidas()) { salida.setEstatus(facturada); salida.setFechaModificacion(fecha); currentSession().update(salida); audita(salida, usuario, Constantes.FACTURADA, fecha); factura.setIva(factura.getIva().add(salida.getIva())); factura.setTotal(factura.getTotal().add(salida.getTotal())); } for (Entrada entrada : factura.getEntradas()) { entrada.setEstatus(facturada); entrada.setFechaModificacion(fecha); currentSession().update(entrada); audita(entrada, usuario, Constantes.FACTURADA, fecha); factura.setIva(factura.getIva().subtract(entrada.getIva())); factura.setTotal(factura.getTotal().subtract(entrada.getTotal())); } query.setString("nombre", Constantes.CERRADA); Estatus estatus = (Estatus) query.uniqueResult(); factura.setEstatus(estatus); factura.setFolio(getFolio(factura.getAlmacen())); factura.setFechaModificacion(fecha); currentSession().update(factura); audita(factura, usuario, Constantes.ACTUALIZAR, fecha); currentSession().flush(); return factura; } else { throw new NoEstaAbiertaException("No se puede actualizar una factura que no este abierta"); } } else { throw new NoSePuedeCerrarException("No se puede cerrar la factura pues no existe"); } }
/** 返回满足条件的文件数量(方法思路同UserDao中的userCount) (注意:File数据库中的name字段有".",不要忘了查询时的单引号) */ public Long fileCount( String name, String s_screateDate, String s_ecreateDate, HttpSession httpSession) throws Exception { User u = (User) httpSession.getAttribute("u"); Long total; if (StringUtil.isNotEmpty(name) || StringUtil.isNotEmpty(s_screateDate) || StringUtil.isNotEmpty(s_ecreateDate)) { // 需要查询的个数 StringBuffer sqlBuffer = new StringBuffer("select count(*) from File file where file.user.id=" + u.getId() + " "); if (StringUtil.isNotEmpty(name)) { sqlBuffer.append("and file.name = '" + name + "' "); } if (StringUtil.isEmpty(s_screateDate)) { s_screateDate = "2010-01-01"; } if (StringUtil.isEmpty(s_ecreateDate)) { // 如果s_ejoindate为空,设s_ejoindate为当前系统时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); s_ecreateDate = df.format(new Date()); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 小写的mm表示的是分钟 Date begin = sdf.parse(s_screateDate); Date end = sdf.parse(s_ecreateDate); sqlBuffer.append("and file.createDate > :beginTime and file.createDate <= :endTime"); Query q = sessionFactory .getCurrentSession() .createQuery(sqlBuffer.toString()) .setTimestamp("beginTime", begin) .setTimestamp("endTime", end); total = (Long) q.uniqueResult(); } else { // 总个数 Query q = sessionFactory .getCurrentSession() .createQuery("select count(*) from File file where file.user.id=" + u.getId()); total = (Long) q.uniqueResult(); } System.out.println(total); return total; }
@Override public String getAmountByShipmentTotalPriceAdj(String orderId) { Session session = getSession(); StringBuilder sb = new StringBuilder(); sb.append("select cd.amount from acoapp_oms.SHIPMENT_TOTALPRICE_ADJ cd"); sb.append(" where cd.order_id = :orderId"); Query q = session.createSQLQuery(sb.toString()); q.setString("orderId", orderId); if (q.uniqueResult() == null) { return "0.00"; } else { return q.uniqueResult().toString(); } }
@Override public List<Forum> getForumsOfaUser(int userId) { // TODO Auto-generated method stub List<Forum> forums = new ArrayList<Forum>(); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from Subscription where userId = :userId"); query.setString("userId", String.valueOf(userId)); List<Subscription> userSubscribedGroups = query.list(); for (Subscription subsc : userSubscribedGroups) { query = session.createQuery("from Forum where forumId = :forumId"); query.setParameter("forumId", subsc.getForumId()); // add this to a list variable query.uniqueResult(); forums.add((Forum) query.uniqueResult()); } } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return forums; }
public User getUser(String username, String psd) { Session session = sessionFactory.getCurrentSession(); Query q = session.createQuery(" from User u where username= :username and psd = :psd"); q.setParameter("username", username); q.setParameter("psd", psd); return (User) q.uniqueResult(); }
@Override public Salary findSalaryById(Integer id) { Query query = getSession().createQuery("from Salary as s where s.id = ?"); query.setString(0, id.toString()); Salary s = (Salary) query.uniqueResult(); return s; }
@SuppressWarnings("unchecked") public OrdemServico buscarPorId(final Long id) { Query q = sessionFactory .getCurrentSession() .createQuery( "SELECT h FROM " + entityClass.getName() + " h " + "LEFT JOIN FETCH h.unidade u " + "LEFT JOIN FETCH h.itemNotaFiscal inf " + "LEFT JOIN FETCH u.equipamento e " + "LEFT JOIN FETCH u.fabricante f " + "LEFT JOIN FETCH u.laboratorio l " + "LEFT JOIN FETCH h.placasFilhas pf " + "LEFT JOIN FETCH pf.orcamento pfOrc " + "LEFT JOIN FETCH pf.reparo pfRep " + "LEFT JOIN FETCH pfOrc.listaDefeito " + "LEFT JOIN FETCH pfRep.listaDefeito " + "LEFT JOIN FETCH h.orcamento orc " + "LEFT JOIN FETCH h.reparo rep " + "LEFT JOIN FETCH orc.listaDefeito " + "LEFT JOIN FETCH rep.listaDefeito WHERE h.id=:id"); q.setParameter("id", id); OrdemServico r = (OrdemServico) q.uniqueResult(); sessionFactory.getCurrentSession().flush(); sessionFactory.getCurrentSession().clear(); return r; }
public Profile findProfileForEmployer(long id) { String queryString = "from EmployerProfile e where e.employer.id= :id "; Query query = getSession().createQuery(queryString); query.setLong("id", id); Profile profile = (Profile) query.uniqueResult(); return profile; }
public static Friend findByUser(User user, User friend) { Session session = getSession(); Query query = session.getNamedQuery("Friend.getByUser"); query.setEntity("inviter", user); query.setEntity("invitee", friend); return (Friend) query.uniqueResult(); }
public static Friend findByInviter(long id, User user) { Session session = getSession(); Query query = session.getNamedQuery("Friend.getByInviter"); query.setLong("id", id); query.setEntity("user", user); return (Friend) query.uniqueResult(); }
public static Friend findByEmail(User user, String email) { Session session = getSession(); Query query = session.getNamedQuery("Friend.getByEmail"); query.setString("email", email); query.setEntity("user", user); return (Friend) query.uniqueResult(); }
@SuppressWarnings("unchecked") public OrdemServico montarConjunto(final Long id) { Query q = sessionFactory .getCurrentSession() .createQuery( "SELECT h FROM " + entityClass.getName() + " h " + "LEFT JOIN FETCH h.unidadePai u " + "LEFT JOIN FETCH h.reparo rep " + "LEFT JOIN FETCH h.orcamento orc " + "WHERE h.id=:id"); q.setParameter("id", id); OrdemServico r = (OrdemServico) q.uniqueResult(); Query q2 = sessionFactory .getCurrentSession() .createQuery( "SELECT h FROM " + entityClass.getName() + " h " + "LEFT JOIN FETCH h.unidadePai u " + "LEFT JOIN FETCH h.reparo rep " + "LEFT JOIN FETCH h.orcamento orc " + "WHERE h.unidadePai.id=:id"); q2.setParameter("id", id); List<OrdemServico> pFilhas = q2.list(); r.setPlacasFilhas(new HashSet<OrdemServico>()); r.getPlacasFilhas().addAll(pFilhas); return r; }
@SuppressWarnings("unchecked") public OrdemServico buscarConsultaId(final Long id) { System.out.println("QUERY DA CONSULTA - INICIO"); Query q = sessionFactory .getCurrentSession() .createQuery( "SELECT h FROM " + entityClass.getName() + " h " + "LEFT JOIN FETCH h.unidade u " + "LEFT JOIN FETCH u.fabricante f " + "LEFT JOIN FETCH u.equipamento e " + "LEFT JOIN FETCH u.laboratorio l " + "LEFT JOIN FETCH h.notaFiscal nf " + "LEFT JOIN FETCH nf.cliente c " + "LEFT JOIN FETCH h.orcamento orc " + "LEFT JOIN FETCH h.reparo rep " + "LEFT JOIN FETCH h.proposta p " + "LEFT JOIN FETCH p.contato cont " + "LEFT JOIN FETCH h.notaFiscalSaida nfs " + "LEFT JOIN FETCH nfs.cliente nfsc " + "LEFT JOIN FETCH nfs.transportador nfst " + "WHERE h.id=:id"); q.setParameter("id", id); OrdemServico r = (OrdemServico) q.uniqueResult(); System.out.println("QUERY DA CONSULTA - FIM"); SessionStatistics sessionStats = sessionFactory.getCurrentSession().getStatistics(); Statistics stats = this.sessionFactory.getStatistics(); System.out.println(stats); return r; }
@Override public User findByNameAndPassword(String name, String password) { Query query = session.createQuery(BY_NAME_AND_PASSWORD_QUERY); query.setString("name", name); query.setString("password", password); return (User) query.uniqueResult(); }
@Override public CommentModel findByIdWithHQLQuery(int commentId) { // Query all properties from model. Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM CommentModel WHERE commentId=:commentId"); query.setParameter("commentId", commentId); CommentModel result = (CommentModel) query.uniqueResult(); // Query partial properties from model. query = session.createQuery( "SELECT new CommentModel(commentContent,commentAuthor) FROM CommentModel WHERE commentId=:commentId"); query.setParameter("commentId", commentId); result = (CommentModel) query.uniqueResult(); return result; }
// User defined finders/Buscadores definidos por el usuario public static FilterBySubfamily findBy() throws javax.ejb.ObjectNotFoundException { if (XavaPreferences.getInstance().isJPAPersistence()) { javax.persistence.Query query = org.openxava.jpa.XPersistence.getManager().createQuery("from FilterBySubfamily as o"); try { return (FilterBySubfamily) query.getSingleResult(); } catch (Exception ex) { // In this way in order to work with Java pre 5 if (ex.getClass().getName().equals("javax.persistence.NoResultException")) { throw new javax.ejb.ObjectNotFoundException( XavaResources.getString("object_not_found", "FilterBySubfamily")); } else { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } } } else { org.hibernate.Query query = org.openxava.hibernate.XHibernate.getSession().createQuery("from FilterBySubfamily as o"); FilterBySubfamily r = (FilterBySubfamily) query.uniqueResult(); if (r == null) { throw new javax.ejb.ObjectNotFoundException( XavaResources.getString("object_not_found", "FilterBySubfamily")); } return r; } }
@Override public Member memberLogin(String login, String password) throws Exception { Session session = HibernateUtil.getSession(); Transaction tx = null; Member member = null; try { String hql = "SELECT a FROM Member AS a WHERE a.login=:login AND a.password=:password"; Query query = session.createQuery(hql); query.setString("login", login.trim()); query.setString("password", password.trim()); query.setMaxResults(1); tx = session.beginTransaction(); member = (Member) query.uniqueResult(); if (member != null && ("y").equals(member.getActivated().toLowerCase())) { member.setLoginTimes(Integer.valueOf(member.getLoginTimes() + 1)); member.setLastLogin(new Date()); session.update(member); } tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); logger.info("In class MemberServiceImpl:memberLogin()\n"); ex.printStackTrace(); } finally { HibernateUtil.closeSession(); } return member; }
public Content getSide( Integer id, Integer siteId, Integer channelId, boolean next, boolean cacheable) { Finder f = Finder.create("from Content bean where 1=1"); if (channelId != null) { f.append(" and bean.channel.id=:channelId"); f.setParam("channelId", channelId); } else if (siteId != null) { f.append(" and bean.site.id=:siteId"); f.setParam("siteId", siteId); } if (next) { f.append(" and bean.id>:id"); f.setParam("id", id); f.append(" and bean.status=" + ContentCheck.CHECKED); f.append(" order by bean.id asc"); } else { f.append(" and bean.id<:id"); f.setParam("id", id); f.append(" and bean.status=" + ContentCheck.CHECKED); f.append(" order by bean.id desc"); } Query query = f.createQuery(getSession()); query.setCacheable(cacheable).setMaxResults(1); return (Content) query.uniqueResult(); }
private String getFolio(Almacen almacen) { Query query = currentSession() .createQuery( "select f from Folio f where f.nombre = :nombre and f.almacen.id = :almacenId"); query.setString("nombre", "FACTURA"); query.setLong("almacenId", almacen.getId()); query.setLockOptions(LockOptions.UPGRADE); Folio folio = (Folio) query.uniqueResult(); if (folio == null) { folio = new Folio("FACTURA"); folio.setAlmacen(almacen); currentSession().save(folio); return getFolio(almacen); } folio.setValor(folio.getValor() + 1); java.text.NumberFormat nf = java.text.DecimalFormat.getInstance(); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(9); nf.setMaximumIntegerDigits(9); nf.setMaximumFractionDigits(0); StringBuilder sb = new StringBuilder(); sb.append("FA-"); sb.append(almacen.getEmpresa().getOrganizacion().getCodigo()); sb.append(almacen.getEmpresa().getCodigo()); sb.append(almacen.getCodigo()); sb.append(nf.format(folio.getValor())); return sb.toString(); }
public PersonalPointScore getPersonalPointScoreByDate(String email, Date date) { Query query = getQuery("from PersonalPointScore p where p.member.email=? and p.createDate=?"); query.setString(0, email); query.setParameter(1, date); return (PersonalPointScore) query.uniqueResult(); }
public int getCountOfSubscribers(int forumId, int userId) { // TODO Auto-generated method stub Session session = this.sessionFactory.openSession(); Transaction tx = null; int countOfSubscribers = 0; try { tx = session.beginTransaction(); Query query = null; if (userId == 0) { query = session.createQuery("select count(*) from Subscription where forumId = :forumId"); query.setParameter("forumId", forumId); } else { query = session.createQuery( "select count(*) from Subscription where forumId = :forumId and userId = :userId"); query.setParameter("forumId", forumId); query.setParameter("userId", userId); } Long count = (Long) query.uniqueResult(); countOfSubscribers = count.intValue(); // System.out.println("No of subscribers.."+countOfSubscribers); } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return countOfSubscribers; }
public Hyjbxx getUserById(Integer id) { String sql = "from Hyjbxx h where h.hyjbxxid=?"; Query query = this.getQuery(sql); query.setParameter(0, id); return (Hyjbxx) query.uniqueResult(); }
// User defined finders/Buscadores definidos por el usuario public static Size findById(int id) throws javax.ejb.ObjectNotFoundException { if (XavaPreferences.getInstance().isJPAPersistence()) { javax.persistence.Query query = org.openxava.jpa.XPersistence.getManager() .createQuery("from Size as o where o.id = :arg0"); query.setParameter("arg0", new Integer(id)); try { return (Size) query.getSingleResult(); } catch (Exception ex) { // In this way in order to work with Java pre 5 if (ex.getClass().getName().equals("javax.persistence.NoResultException")) { throw new javax.ejb.ObjectNotFoundException( XavaResources.getString("object_not_found", "Size")); } else { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } } } else { org.hibernate.Query query = org.openxava.hibernate.XHibernate.getSession() .createQuery("from Size as o where o.id = :arg0"); query.setParameter("arg0", new Integer(id)); Size r = (Size) query.uniqueResult(); if (r == null) { throw new javax.ejb.ObjectNotFoundException( XavaResources.getString("object_not_found", "Size")); } return r; } }
public int getMessageSizeByToId(int toId) { String sql = "select count(*) from Message m where m.toid=?"; Query query = this.getQuery(sql); query.setParameter(0, toId); Object count = query.uniqueResult(); return ((Long) count).intValue(); }
public Pager findAllUnconfirmedByProbationUnitId( String referenceId, Integer start, Integer size) { Pager pager = new Pager(); start = (start == null) ? 0 : start; pager.setStart(start); size = (size == null) ? Pager.DEFAULT_PAGE_SIZE : size; pager.setSize(size); Query queryCount = getSession() .createQuery( "select count(ct) from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0"); queryCount.setParameter("pid", referenceId); int listCount = ((Long) queryCount.uniqueResult()).intValue(); pager.setTotal(listCount); Query query = getSession() .createQuery( "select ct from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0"); query.setParameter("pid", referenceId); query.setFirstResult(start); query.setMaxResults(size); @SuppressWarnings("unchecked") List<ChildTransfer> list = query.list(); pager.setList(list); return pager; }
public int getBuySizeMessageByType(int type) { String sql = "select count(*) from Message m where m.type=?"; Query query = this.getQuery(sql); query.setParameter(0, type); Object count = query.uniqueResult(); return ((Long) count).intValue(); }