/** * Permet de créer un Blob à partir d'un stream sans indiquer/connaître la taille. Fonctionne uniquement avec jdbc4. Une exception est * lancée si jdbc4 n'est pas présent. * * @param aInputStream * @return */ public Blob createBlob(InputStream aInputStream) { final LobCreator lobCreator = Hibernate.getLobCreator(session); // // JDBC4 -> pas besoin de la taille // if (lobCreator instanceof ContextualLobCreator) { // // Passage de -1 comme taille: De toutes façons cette valeur n'est pas utilisée en jdbc4 // return lobCreator.createBlob(aInputStream, -1); // } // else { // Fallback JDBC3 // On récupère le stream pour connaitre la taille final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(aInputStream, bos); return lobCreator.createBlob(new ByteArrayInputStream(bos.toByteArray()), bos.size()); } catch (IOException ioe) { throw new RuntimeException(ioe); } // } }
/** * Remove a product from a collection. The product should stay in the * database. * * @param cid the collection id where remove product. * @param pid the product id to remove. * @param user unused parameter. */ public void removeProduct (final String cid, final Long pid, User user) { Collection collection = read(cid); if (collection == null) { LOGGER.warn("Unknown collection #" + cid); return; } Product product = productDao.read(pid); if (product == null) { LOGGER.warn("Unknown product #" + pid); return; } Hibernate.initialize (collection.getProducts()); collection.getProducts().remove(product); update(collection); fireProductRemoved (new DaoEvent<> (collection), product); }
@Override public void delete () { Long id = 1L; FileScanner element = dao.read (id); Set<Collection> collections = element.getCollections (); Hibernate.initialize (collections); dao.delete (element); assertEquals (dao.count (), (howMany () - 1)); assertNull (dao.read (id)); for (Collection collection : collections) { assertNotNull (cdao.read (collection.getUUID ())); } }
@Override @Test (dependsOnMethods = { "read", "create" }) public void delete () { long id = 1; Eviction eviction = dao.read (id); Set<Product> ps = eviction.getProducts (); Hibernate.initialize (ps); dao.delete (eviction); assertEquals (dao.count (), (howMany () - 1)); assertNull (dao.read (id)); for (Product p : ps) { assertNotNull (pdao.read (p.getId ())); } }
protected <T> T unproxyEntity(T template) { if (template instanceof HibernateProxy) { Hibernate.initialize(template); template = (T) ((HibernateProxy) template) .getHibernateLazyInitializer() .getImplementation(); } return template; }
@SuppressWarnings("unchecked") public T getById(Long pk) throws SQLException { Session session = HibernateUtil.getSessionFactory().openSession(); T entity = null; try { session.beginTransaction(); entity = (T) session.get(getEntityClass(), pk); Hibernate.initialize(entity); session.getTransaction().commit(); } catch (HibernateException hibernateException) { session.getTransaction().rollback(); throw new SQLException(hibernateException); } finally { session.close(); } return entity; }
@Override public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException { String dbValue = Hibernate.STRING.nullSafeGet(rs, names[0]); if( dbValue != null ) { return unescape(dbValue); } else { return null; } }
private EntryCache createMappings(List<MimeEntry> entries) { Map<String, MimeEntry> mappedEntries = new HashMap<String, MimeEntry>(); Map<String, MimeEntry> mimeEntries = new HashMap<String, MimeEntry>(); for( MimeEntry mimeEntry : entries ) { Collection<String> extensions = mimeEntry.getExtensions(); // Load it all up Hibernate.initialize(mimeEntry.getAttributes()); for( String ext : extensions ) { mappedEntries.put(ext, mimeEntry); } mimeEntries.put(mimeEntry.getType(), mimeEntry); } return new EntryCache(mappedEntries, mimeEntries); }
@Override protected ComparisonEntityInitialiser<ItemDefinition> getComparisonInitialiserForStopEdit() { return new ComparisonEntityInitialiser<ItemDefinition>() { @Override public void preUnlink(ItemDefinition t) { // We suck the big one for misusing hibernate. initBundle(t.getName()); initBundle(t.getDescription()); t.getItemMetadataRules(); Hibernate.initialize(t.getWorkflow()); } }; }
@Override public boolean reassociateIfUninitializedProxy(Object value) throws MappingException { if ( value instanceof ElementWrapper ) { value = ( (ElementWrapper) value ).getElement(); } if ( !Hibernate.isInitialized( value ) ) { final HibernateProxy proxy = (HibernateProxy) value; final LazyInitializer li = proxy.getHibernateLazyInitializer(); reassociateProxy( li, proxy ); return true; } else { return false; } }
protected void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException { if ( value == null ) { st.setNull( index, sqlTypes( null )[0] ); } else { byte[] toSet = unWrap( value ); final boolean useInputStream = session.getFactory().getDialect().useInputStreamToInsertBlob(); if ( useInputStream ) { st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length ); } else { st.setBlob( index, Hibernate.getLobCreator( session ).createBlob( toSet ) ); } } }
private WrapperOptions getOptions(final SessionImplementor session) { return new WrapperOptions() { public boolean useStreamForLobBinding() { return Environment.useStreamsForBinary() || session.getFactory().getDialect().useInputStreamToInsertBlob(); } public LobCreator getLobCreator() { return Hibernate.getLobCreator( session ); } public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) { final SqlTypeDescriptor remapped = sqlTypeDescriptor.canBeRemapped() ? session.getFactory().getDialect().remapSqlTypeDescriptor( sqlTypeDescriptor ) : sqlTypeDescriptor; return remapped == null ? sqlTypeDescriptor : remapped; } }; }
private static DetachedCriteria createEcrfFieldStatusEntryDetachedCriteriaMaxId(org.hibernate.Criteria ecrfFieldStatusEntryCriteria, org.hibernate.Criteria ecrfFieldCriteria, org.hibernate.Criteria probandListEntryCriteria, ECRFFieldStatusQueue queue, Long probandListEntryId, Long ecrfFieldId) { DetachedCriteria subQuery = createEcrfFieldStatusEntryDetachedCriteria(ecrfFieldStatusEntryCriteria, ecrfFieldCriteria, probandListEntryCriteria, probandListEntryId, ecrfFieldId); if (queue != null) { subQuery.add(Restrictions.eq("queue", queue)); subQuery.setProjection(Projections.max("id")); } else { ProjectionList proj = Projections.projectionList(); proj.add(Projections.sqlGroupProjection( "max({alias}.id) as maxId", "{alias}.queue", new String[] { "maxId" }, new org.hibernate.type.Type[] { Hibernate.LONG })); subQuery.setProjection(proj); } return subQuery; }
@Nonnull public LocalisedString getHomeMunicipalityName() { if (this.homeMunicipality != null) { if (!Hibernate.isInitialized(this.homeMunicipality)) { try { // Referenced row might not exist return this.homeMunicipality.getNameLocalisation(); } catch (UnresolvableObjectException | EntityNotFoundException o) { this.homeMunicipality = null; } } else { return this.homeMunicipality.getNameLocalisation(); } } return LocalisedString.EMPTY; }
public List getShelterIds(String provider_no) { String sql ="select distinct c.id as shelter_id from lst_shelter c, lst_orgcd a, secUserRole b where instr('RO',substr(b.orgcd,1,1)) = 0 and a.codecsv like '%' || b.orgcd || ',%'" + " and b.provider_no=? and a.codecsv like '%S' || c.id || ',%'"; Session session = getSession(); Query query = session.createSQLQuery(sql); ((SQLQuery) query).addScalar("shelter_id", Hibernate.INTEGER); query.setString(0, provider_no); List lst = new ArrayList(); try { lst=query.list(); }finally { this.releaseSession(session); } return lst; }
@Override public void addImagePost(final Title title, final byte[] data) { final Session session = entityManager.unwrap(Session.class); final Blob blob = Hibernate.getLobCreator(session).createBlob(data); final StoredImage storedImage = new StoredImage(); storedImage.setData(blob); final ImagePost imagePost = ImagePost.builder() .withPoints(0L) .withNumComments(0L) .withTitle(title) .withStoredImage(storedImage) .build(); entityManager.persist(imagePost); }
@Override public void execute() { try{ Transaction tx = session.beginTransaction(); String query = "SELECT distinct(u.user_id) FROM users u,signing s where u.sys_id=s.sys_id and :date > all(select s1.until_date from signing s1 where u.sys_id=s1.sys_id) and not exists (select l.sys_id from lending l where l.sys_id = u.sys_id and return_date is null)"; Query q = session.createSQLQuery(query); q.setParameter("date",date, Hibernate.DATE); list = q.list(); query = "SELECT u.user_id FROM users u where not exists(select s.sys_id from signing s where u.sys_id=s.sys_id) and not exists (select l.sys_id from lending l where l.sys_id = u.sys_id and return_date is null)"; q = session.createSQLQuery(query); list.addAll(q.list()); tx.commit(); }catch (Exception e){ log.error(e); } }
@Override public void execute() { try{ Transaction tx = session.beginTransaction(); SQLQuery q = session.createSQLQuery("select sys_id from lending l where l.return_date is null and l.ctlg_no = :ctlgno"); q.setString("ctlgno", ctlgno); Iterator it = q.list().iterator(); if (it.hasNext()){ Integer sysid = (Integer)it.next(); q = session.createSQLQuery("select user_id, first_name, last_name from users u where u.sys_id = :sysid") .addScalar("user_id", Hibernate.STRING).addScalar("first_name", Hibernate.STRING).addScalar("last_name", Hibernate.STRING); q.setInteger("sysid", sysid); it = q.list().iterator(); if (it.hasNext()){ user = (Object[])it.next(); } } tx.commit(); }catch (Exception e){ log.error("loading chargde user failed"); log.error(e); } }
@Override public void execute() { try{ Transaction tx = session.beginTransaction(); Query crt; if (!location.equals(" ")) { String loc = ((Location) location).getName(); String query1 = "select count(*) from Users u inner join u. signings as s where " + " (s.location.name= :loc) and (s.signDate between :start and :end)"; crt = session.createQuery(query1).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP).setString("loc", loc); } else { String query2 = "select count(*) from Users u inner join u. signings as s where " + " (s.signDate between :start and :end)"; crt = session.createQuery(query2).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP); } if (crt != null) { list = crt.list(); } tx.commit(); log.info("Statistic1 report"); }catch (Exception e){ log.error("Statistic1 report failed"); log.error(e); } }
/** * {@inheritDoc} * * @see com.communote.server.core.ConfigurationManagementBase#handleGetClientLogo() */ @Override protected ImageVO handleGetClientLogo() { Configuration configuration = handleGetConfiguration(); ImageVO result = null; ClientConfiguration clientConfig = configuration.getClientConfig(); if (clientConfig != null) { if (!Hibernate.isInitialized(clientConfig.getLogoImage())) { Hibernate.initialize(clientConfig.getLogoImage()); } if (clientConfig.getLogoImage() != null) { result = new ImageVO(); result.setImage(configuration.getClientConfig().getLogoImage()); Timestamp date = configuration.getClientConfig().getLastLogoImageModificationDate(); // use timestamp 0 if it is not yet set due to migration result.setLastModificationDate(date == null ? new Date(0) : date); } } return result; }
@Override public void execute() { try{ Transaction tx = session.beginTransaction(); Query crt; if (!location.equals(" ")) { String loc = ((Location) location).getName(); String query1 = "select distinct l.ctlgNo from Lending l where " + " (l.location.name= :loc) and (l.resumeDate between :start and :end) "; crt = session.createQuery(query1).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP).setString("loc", loc); } else { String query2 = "select distinct l.ctlgNo from Lending l where " + " (l.resumeDate between :start and :end) "; crt = session.createQuery(query2).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP); } if (crt != null) { list = crt.list(); } tx.commit(); log.info("Statistic8 report"); }catch (Exception e){ log.error("Statistic8 report failed"); log.error(e); } }
public void testGetCustomerJson() throws Exception { EntityManager em = emf.createEntityManager(); // false -> no forcing of lazy loading Customer customer = em.find(Customer.class, 103); assertFalse(Hibernate.isInitialized(customer.getPayments())); String json = JSON.toJSONString(customer); System.out.println(json); // should force loading... // Set<Payment> payments = customer.getPayments(); // /* // System.out.println("--- JSON ---"); // System.out.println(json); // System.out.println("--- /JSON ---"); // */ // // assertTrue(Hibernate.isInitialized(payments)); // // TODO: verify // assertNotNull(json); // // Map<?,?> stuff = mapper.readValue(json, Map.class); // // assertTrue(stuff.containsKey("payments")); // assertTrue(stuff.containsKey("orders")); // assertNull(stuff.get("orderes")); }
protected Blob createBlob(MultipartFile file) { try { Session session = entityManager.unwrap(Session.class); return Hibernate.getLobCreator(session).createBlob(file.getInputStream(), file.getSize()); } catch (Exception e) { throw new CantCreateBlobException(e); } }
@Override public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { boolean init = Hibernate.isInitialized(obj); out.writeObject(init ? obj : null); out.flush(); return; }
@SuppressWarnings({"unchecked", "rawtypes"}) public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (Hibernate.isInitialized(obj)) { delegate.writeObject(new ArrayList((Collection) obj), out); } else { delegate.writeObject(new ArrayList(), out); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (Hibernate.isInitialized(obj)) { delegate.writeObject(new HashMap((Map) obj), out); } else { delegate.writeObject(new HashMap(), out); } }
public User uploadimg(File file, Long userId) throws IOException { Session session = getSession(); User loginUser = get(User.class,userId); loginUser.setHeaderpic(Hibernate.getLobCreator(session).createBlob(IOUtils.readFileToArray(file))); //图像文件的后缀名 loginUser.setPicExtName(file.getName().substring(file.getName().lastIndexOf("."))); session.save(loginUser); return loginUser; }
@Override public StudentUser findStudentByEmail(String email) { logger.info("email : {}", email); Criteria crit = createEntityCriteria(); crit.add(Restrictions.eq("email", email)); StudentUser user = (StudentUser) crit.uniqueResult(); if (user != null) { Hibernate.initialize(user.getUserRoles()); } return user; }
public AdmUser findById(int id) { AdmUser user = getByKey(id); if (user != null) { Hibernate.initialize(user.getUserRoles()); } return user; }
public AdmUser findBySSO(String email) { logger.info("email : {}", email); Criteria crit = createEntityCriteria(); crit.add(Restrictions.eq("email", email)); AdmUser user = (AdmUser) crit.uniqueResult(); if (user != null) { Hibernate.initialize(user.getUserRoles()); } return user; }
@Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Cacheable (value = {"indexes"}, key = "#product_id") public List<MetadataIndex> getIndexes(Long product_id) { Product product = productDao.read (product_id); if (product == null) return new ArrayList<MetadataIndex> (); Hibernate.initialize (product.getIndexes ()); return product.getIndexes (); }
@Transactional (readOnly=true, propagation=Propagation.REQUIRED) public Product getProductWithIndexes(Long product_id) { Product product = productDao.read (product_id); if (product == null) return null; Hibernate.initialize (product.getIndexes ()); return product; }
/** * Get the cart of the related user. If the user has no cart configured, null * is returned. * @param uuid the related user to retrieve the cart. * @return the cart * @throws UserNotExistingException when passed user is unknown. */ @PreAuthorize ("hasRole('ROLE_DOWNLOAD')") @Transactional (readOnly=true, propagation=Propagation.REQUIRED) public ProductCart getCartOfUser(String uuid) throws UserNotExistingException { User user = getUser (uuid); ProductCart pc = productCartDao.getCartOfUser(user); if (pc != null) { Hibernate.initialize(pc.getProducts()); } return pc; }
@Test public void testWithGraphControlWithoutJoin() { JpaQueryExecutor<TestEntity> exec = builder().buildExecutor().fetch(Arrays.asList(TestEntity.ATTR_oneRelatedValue)); for (TestEntity test : exec.getResultList()) { assertTrue(Hibernate.isInitialized(test)); RelatedEntity relatedValue = test.getOneRelatedValue(); if (relatedValue != null) { assertTrue(Hibernate.isInitialized(relatedValue)); } } }
@Test public void testWithGraphControlWithJoin() { JpaQueryExecutor<TestEntity> exec = builder().addFilter(TestEntity.ATTR_oneRelatedValue, FilterOperator.NEQ, null).buildExecutor().fetch(Arrays.asList(TestEntity.ATTR_oneRelatedValue)); for (TestEntity test : exec.getResultList()) { assertTrue(Hibernate.isInitialized(test)); assertTrue(Hibernate.isInitialized(test.getOneRelatedValue())); } }
@Test public void testWithoutGraphControl() { JpaQueryExecutor<TestEntity> exec = builder().addFilter(TestEntity.ATTR_oneRelatedValue, FilterOperator.NEQ, null).buildExecutor(); for (TestEntity test : exec.getResultList()) { RelatedEntity relatedValue = test.getOneRelatedValue(); assertTrue(Hibernate.isInitialized(test)); assertFalse(Hibernate.isInitialized(relatedValue)); } }
@Test public void testIncludeNoRelations() throws InstantiationException, IllegalAccessException { em.clear(); List<TestEntity> list = repo.findAll(new QuerySpec(TestEntity.class)); Assert.assertEquals(numTestEntities, list.size()); for (TestEntity entity : list) { RelatedEntity relatedValue = entity.getOneRelatedValue(); if (relatedValue != null) Assert.assertFalse(Hibernate.isInitialized(relatedValue)); } }
private User initializeUser(User u) { Hibernate.initialize(u.getLikes()); Hibernate.initialize(u.getCommunities()); Hibernate.initialize(u.getRoles()); Hibernate.initialize(u.getUserContacts()); Hibernate.initialize(u.getPrivateMessagesReceiver()); Hibernate.initialize(u.getPrivateMessagesSender()); return u; }
/** * Get one attachment by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Attachment findOneWithContent(Long id) { log.debug("Request to get Attachment : {}", id); Attachment attachment = attachmentRepository.findOne(id); if (attachment != null) { Hibernate.initialize(attachment.getContent()); } return attachment; }
public A getInitializedWithHibernate(long id){ A a = em.find(A.class, id); if(a == null){ return null; } //If you are using Hibernate, you can also use the following Hibernate.initialize(a.getList()); return a; }