Java 类org.hibernate.impl.SessionFactoryImpl 实例源码

项目:hazelcast-hibernate    文件:RegionFactoryDefaultSlowTest.java   
@Test
public void testQueryCacheCleanup() {
    MapConfig mapConfig = getHazelcastInstance(sf).getConfig().getMapConfig("org.hibernate.cache.*");
    final float baseEvictionRate = 0.2f;
    final int numberOfEntities = 100;
    final int defaultCleanupPeriod = 60;
    final int maxSize = mapConfig.getMaxSizeConfig().getSize();
    final int evictedItemCount = numberOfEntities - maxSize + (int) (maxSize * baseEvictionRate);
    insertDummyEntities(numberOfEntities);
    sleep(1);
    for (int i = 0; i < numberOfEntities; i++) {
        executeQuery(sf, i);
    }

    HazelcastQueryResultsRegion queryRegion = ((HazelcastQueryResultsRegion) (((SessionFactoryImpl) sf).getQueryCache()).getRegion());
    assertEquals(numberOfEntities, queryRegion.getCache().size());
    sleep(defaultCleanupPeriod);

    assertEquals(numberOfEntities - evictedItemCount, queryRegion.getCache().size());
}
项目:cacheonix-core    文件:Configuration.java   
/**
 * Instantiate a new <tt>SessionFactory</tt>, using the properties and
 * mappings in this configuration. The <tt>SessionFactory</tt> will be
 * immutable, so changes made to the <tt>Configuration</tt> after
 * building the <tt>SessionFactory</tt> will not affect it.
 *
 * @return a new factory for <tt>Session</tt>s
 * @see org.hibernate.SessionFactory
 */
public SessionFactory buildSessionFactory() throws HibernateException {
    log.debug( "Preparing to build session factory with filters : " + filterDefinitions );
    secondPassCompile();
    validate();
    Environment.verifyProperties( properties );
    Properties copy = new Properties();
    copy.putAll( properties );
    PropertiesHelper.resolvePlaceHolders( copy );
    Settings settings = buildSettings( copy );

    return new SessionFactoryImpl(
            this,
            mapping,
            settings,
            getInitializedEventListeners()
        );
}
项目:Equella    文件:HibernateMigrationHelper.java   
public HibernateMigrationHelper(HibernateFactory factory, String defaultSchema)
{
    this.factory = (SessionFactoryImpl) factory.getSessionFactory();
    dialect = this.factory.getDialect();
    extDialect = (ExtendedDialect) dialect;
    this.configuration = factory.getConfiguration();
    mapping = configuration.buildMapping();
    this.defaultSchema = defaultSchema;
    defaultCatalog = null;
}
项目:openbravo-brazil    文件:OBDal.java   
/**
 * Register a sql function in the session factory, after this call it can be used by queries.
 */
public void registerSQLFunction(String name, SQLFunction function) {
  final DalSessionFactory dalSessionFactory = (DalSessionFactory) SessionFactoryController
      .getInstance().getSessionFactory();

  final Dialect dialect = ((SessionFactoryImpl) dalSessionFactory.getDelegateSessionFactory())
      .getDialect();
  dialect.getFunctions().put(name, function);
}
项目:communote-server    文件:TestUtils.java   
/**
 * Creates a new note and stores in within the db.
 *
 * @param topic
 *            The topic.
 * @param creatorId
 *            The creator.
 * @param content
 *            The content.
 * @param attachmentIds
 *            List of attachments for note.
 * @param parentNoteId
 *            If not null, this note will be reply to the given parent note.
 * @param creationDate
 *            The creation date of the note.
 * @return Id of the created note.
 * @throws TestUtilsException
 *             Exception.
 */
public static Long createAndStoreCommonNote(Blog topic, Long creatorId, String content,
        Long[] attachmentIds, Long parentNoteId, Date creationDate) throws TestUtilsException {
    NoteStoringTO note = createCommonNote(topic, creatorId, content, attachmentIds);
    note.setParentNoteId(parentNoteId);
    note.setCreationDate(creationDate == null ? null : new Timestamp(creationDate.getTime()));
    try {
        Long noteId;
        if (parentNoteId == null) {
            noteId = ServiceLocator.findService(NoteService.class)
                    .createNote(note, new HashSet<String>()).getNoteId();
        } else {
            note.setParentNoteId(parentNoteId);
            noteId = ServiceLocator.findService(NoteService.class).createNote(note, null)
                    .getNoteId();
        }
        // TODO why manually evicting the just created note? Well could be useful for tests
        // where the creationDate or modificationDate of the created note is used in further
        // operations that query the database. MySQL has only seconds-precision. When getting
        // the note it is loaded from cache which still has the date with milliseconds and not
        // the value that was stored in database. Maybe we should optimize this with an
        // additional boolean parameter that when true will evict the note.
        ServiceLocator.instance().getService("sessionFactory", SessionFactoryImpl.class)
                .getCache().evictEntity(Note.class, noteId);
        return noteId;
    } catch (BlogNotFoundException | NoteStoringPreProcessorException
            | NoteManagementAuthorizationException e) {
        throw new TestUtilsException(e);
    }
}
项目:haloDao-Hibernate3    文件:HibernateUtils.java   
/**
 * hql转sql
 * 
 * @param hql
 * @return sql语句
 */
public static String hqlToSql(String hql,SessionFactory sessionFactory) {
    SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
    QueryTranslatorFactory queryTranslatorFactory = sessionFactoryImpl.getSettings().getQueryTranslatorFactory();
    FilterTranslator filterTranslator = queryTranslatorFactory.createFilterTranslator(hql, hql, Collections.EMPTY_MAP, sessionFactoryImpl);
    filterTranslator.compile(Collections.EMPTY_MAP, false);
    return filterTranslator.getSQLString();
}
项目:haloDao-Hibernate3    文件:HibernateUtils.java   
/**
 *  TODO 占位符方式转sql
 * @param hql
 * @param sessionFactory
 * @return
 */
public static String hqlToSqlByPlaceholder(String hql,SessionFactory sessionFactory) {
    SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
    QueryTranslatorFactory queryTranslatorFactory = sessionFactoryImpl.getSettings().getQueryTranslatorFactory();
    FilterTranslator filterTranslator = queryTranslatorFactory.createFilterTranslator(hql, hql, Collections.EMPTY_MAP, sessionFactoryImpl);
    filterTranslator.compile(Collections.EMPTY_MAP, false);
    String sql=filterTranslator.getSQLString();
    return getPlaceholderSql(hql, sql);
}
项目:zswxsqxt    文件:BaseHibernateDao.java   
/**
 * 取得XsqlBuilder对象
 * @return 返回XsqlBuilder对象
 */
protected XsqlBuilder getXsqlBuilder() {
    SessionFactoryImpl sf = (SessionFactoryImpl)(getSessionFactory());
    Dialect dialect = sf.getDialect();

    //or SafeSqlProcesserFactory.getMysql();
    SafeSqlProcesser safeSqlProcesser = SafeSqlProcesserFactory.getFromCacheByHibernateDialect(dialect); 
    XsqlBuilder builder = new XsqlBuilder(safeSqlProcesser);

    if(builder.getSafeSqlProcesser().getClass() == DirectReturnSafeSqlProcesser.class) {
        System.err.println(BaseHibernateDao.class.getSimpleName()+".getXsqlBuilder(): 故意报错,你未开启Sql安全过滤,单引号等转义字符在拼接sql时需要转义,不然会导致Sql注入攻击的安全问题,请修改源码使用new XsqlBuilder(SafeSqlProcesserFactory.getDataBaseName())开启安全过滤");
    }
    return builder;
}
项目:Equella    文件:HibernateMigrationHelper.java   
public SessionFactoryImpl getFactory()
{
    return factory;
}
项目:cacheonix-core    文件:DynamicFilterTest.java   
public void testSecondLevelCachedCollectionsFiltering() {
    TestData testData = new TestData();
    testData.prepare();

    Session session = openSession();

    // Force a collection into the second level cache, with its non-filtered elements
    Salesperson sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
    Hibernate.initialize( sp.getOrders() );
    CollectionPersister persister = ( ( SessionFactoryImpl ) getSessions() )
            .getCollectionPersister( Salesperson.class.getName() + ".orders" );
    assertTrue( "No cache for collection", persister.hasCache() );
    CollectionCacheEntry cachedData = ( CollectionCacheEntry ) persister.getCache().getCache()
            .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) );
    assertNotNull( "collection was not in cache", cachedData );

    session.close();

    session = openSession();
    session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
    sp = ( Salesperson ) session.createQuery( "from Salesperson as s where s.id = :id" )
            .setLong( "id", testData.steveId.longValue() )
            .uniqueResult();
    assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );

    CollectionCacheEntry cachedData2 = ( CollectionCacheEntry ) persister.getCache().getCache()
            .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) );
    assertNotNull( "collection no longer in cache!", cachedData2 );
    assertSame( "Different cache values!", cachedData, cachedData2 );

    session.close();

    session = openSession();
    session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
    sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
    assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );

    session.close();

    // Finally, make sure that the original cached version did not get over-written
    session = openSession();
    sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
    assertEquals( "Actual cached version got over-written", 2, sp.getOrders().size() );

    session.close();
    testData.release();
}
项目:salasanasiilo    文件:PasswordDAOHibernate.java   
@Override
@SuppressWarnings("unchecked")
public List<Password> findPasswordByFuzzySearch(String query, User user, boolean activeOnly, Collection<Tag> tags, Match tagMatch)
{
    //kludge to not use ilike on text column if MSSQL
    boolean isMSSQL = ((SessionFactoryImpl)getSessionFactory()).getDialect().toString().contains("SQLServer");
    Criteria crit = getSession().createCriteria(getPersistentClass());
    crit.setFetchMode("tags", FetchMode.JOIN);
    crit.add(Restrictions.or(Restrictions.or(Restrictions.ilike("name", query, MatchMode.ANYWHERE), 
            Restrictions.ilike("username", query, MatchMode.ANYWHERE)), isMSSQL ? 
            Restrictions.like("notes", query, MatchMode.ANYWHERE) : 
            Restrictions.ilike("notes", query, MatchMode.ANYWHERE)));
    if (activeOnly)
    {
        crit.add(Restrictions.eq("active", true));
    }
    Criterion tagsCriterion = null;
    for (Tag tag : tags)
    {
        Criterion tc = Restrictions.sqlRestriction("? in (select tag_id from password_tags where password_id = {alias}.id)", tag.getId(), StandardBasicTypes.LONG); 
        if (null == tagsCriterion)
        {
            tagsCriterion = tc;
        }
        else
        {
            tagsCriterion = tagMatch.equals(Match.AND) ? Restrictions.and(tagsCriterion, tc) : Restrictions.or(tagsCriterion, tc);
        }
    }
    if (tagsCriterion != null) crit.add(tagsCriterion);
    crit.createAlias("permissions", "pm");
    crit.add(Restrictions.in("pm.accessLevel", 
            new String[] {AccessLevel.READ.name(), AccessLevel.WRITE.name(), AccessLevel.GRANT.name()}));
    if (!authorizer.isAuthorized(user, Function.BYPASS_PASSWORD_PERMISSIONS.name()))
    {
        DetachedCriteria groupQuery = DetachedCriteria.forClass(Group.class);
        groupQuery.setProjection(Projections.id());
        groupQuery.createCriteria("users", "u").add(Restrictions.eq("u.id", user.getId()));
        crit.add(Restrictions.or(Restrictions.eq("pm.subject", user), Subqueries.propertyIn("pm.subject", groupQuery)));
    }
    crit.addOrder(Order.asc("name"));
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return crit.list();
}
项目:Improve    文件:HibernateTest.java   
public void testBuild() throws Exception {
    // 持久类对象描述
    RenderClass rc = new RenderClass();
    ArrayList list = new ArrayList();

    RenderProperty property = new RenderProperty();
    // 添加主键
    property.setName("oid");
    property.setField("oid");
    property.setLength(new Integer(15));
    property.setPrimary(true);
    property.setType(Long.class.getName());
    //property.setSequence("SEQ_PERSON");

    list.add(property);
    // 添加一个name字段
    property = new RenderProperty();
    property.setName("name");
    property.setType(String.class.getName());
    property.setField("name");
    property.setLength(new Integer(20));

    list.add(property);

    rc.setProperties(list);
    // 类名
    rc.setClassName("com.rayleigh.asm.bean.Person");
    rc.setTableName("person1");
    // 开始生成class
    POBuildUtil util = new POBuildUtil();
    util.build(rc.getClassName(),
            //G:\javaSoft\excelutil\bin\com\rayleigh\asm\bean
            "G:\\javaSoft\\excelutil\\bin\\com\\rayleigh\\asm\\bean\\Person.class",
            list);
    // 实例化一个person
    Object person = Class.forName("com.rayleigh.asm.bean.Person").newInstance();// hbmcls.newInstance();

    // 开始生成hbm.xml
    FreemarkerRender render = new FreemarkerRender();
    render.render(rc, Templates.TEMPLATE_HIBERNATE3,
            "G:\\javaSoft\\excelutil\\bin\\com\\rayleigh\\asm\\bean\\person.hbm.xml");
    URL url = this.getClass().getResource("/com/rayleigh/asm/bean/person.hbm.xml");
    config.addURL(url);
    // 更新hibernate.cfg.xml
    HibernateUtil.updateHbmCfg(
            this.getClass().getResource(
                    "/com/rayleigh/hibernate/hibernate.cfg.xml"),
            "com/rayleigh/asm/bean/person.hbm.xml");

    PersistentClass model = config.getClassMapping("com.rayleigh.asm.bean.Person");
    // sessionFactory哪下子,快接纳person爷爷进去
    ((SessionFactoryImpl) factory).addPersistentClass(model,
            config.getMapping());
    // 生成数据库
    SchemaExport export = new SchemaExport(config,
            ((SessionFactoryImpl) factory).getSettings());
    export.execute(true, true, false, true);
    // 测试一下,随便给个名字什么的
    PropertyUtils.setProperty(person, "name", "rayleigh");
    Session session = factory.openSession();
    Transaction tran = session.beginTransaction();
    try {
        // 保存
        session.save(person);
        tran.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tran.rollback();
    } finally {
        session.close();
    }
}