org.hibernate.Session#get ( )源码实例Demo

下面列出了org.hibernate.Session#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: uyuni   文件: HibernateFactory.java
/**
 * Return a locked persistent instance of the given entity class with
 * the given identifier, or null if there is no such persistent instance.
 * (If the instance, or a proxy for the instance, is already associated
 * with the session, return that instance or proxy.)
 * @param clazz a persistent class
 * @param id an identifier
 * @return Object persistent instance or null
 */
protected Object lockObject(Class clazz, Serializable id) {
    Object retval = null;
    Session session = null;

    try {
        session = HibernateFactory.getSession();

        retval = session.get(clazz, id, LockMode.UPGRADE);
    }
    catch (MappingException me) {
        getLogger().error("Mapping not found for " + clazz.getName(), me);

    }
    catch (HibernateException he) {
        getLogger().error("Hibernate exception: " + he.toString());
    }

    return retval;
}
 
源代码2 项目: J2Cache   文件: J2CacheProviderTester.java
@After
public void testDelete() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    try {
        User user = (User) session.get(User.class, 1);
        assertTrue(user != null);
        session.delete(user);
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        session.close();
    }
}
 
源代码3 项目: Project   文件: CRUDTest.java
@Test
public void updateTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = session.get(User.class, 1);
    user.setUsername("gjxaiou");
    session.update(user);

    transaction.commit();

    session.close();
    sessionFactory.close();
}
 
源代码4 项目: cacheonix-core   文件: ArrayTest.java
public void testArrayJoinFetch() throws Exception {
	Session s;
	Transaction tx;
	s = openSession();
	tx = s.beginTransaction();
	A a = new A();
	B b = new B();
	a.setBs( new B[] {b} );
	s.persist( a );
	tx.commit();
	s.close();

	s = openSession();
	tx = s.beginTransaction();
	a = (A) s.get( A.class, a.getId() );
	assertNotNull( a );
	assertNotNull( a.getBs() );
	assertEquals( a.getBs().length, 1 );
	assertNotNull( a.getBs()[0] );
	
	s.delete(a);
	s.delete(a.getBs()[0]);
	tx.commit();
	s.close();
}
 
源代码5 项目: spacewalk   文件: UserFactory.java
/**
 * Sets a UserServerPreference to true or false
 * @param user User whose preference will be set
 * @param server Server we are setting the perference on
 * @param preferenceName the name of the preference
 * @see com.redhat.rhn.domain.user.UserServerPreferenceId
 * @param value true if the preference should be true, false otherwise
 */
public void setUserServerPreferenceValue(User user,
        Server server,
        String preferenceName,
        boolean value) {
    Session session = HibernateFactory.getSession();
    UserServerPreferenceId id = new UserServerPreferenceId(user,
            server,
            preferenceName);
    UserServerPreference usp = (UserServerPreference)
            session.get(UserServerPreference.class, id);

    /* Here, we delete the preference's entry if it should be true.
     * We would hopefully be ok setting the value to "1," but I'm emulating
     * the Perl side here just to be safe
     */
    if (value) {
        if (usp != null) {
            session.delete(usp);
        }
    }
    else {
        if (usp == null) {
            id = new UserServerPreferenceId(user, server, preferenceName);
            usp = new UserServerPreference();
            usp.setId(id);
            usp.setValue("0");
            session.save(usp);
        }
    }
}
 
源代码6 项目: kardio   文件: TestDaoService.java
public K8sApiStatusEntity createK8sApiStatusEntity(Session session, String envName) {
    K8sApiStatusEntity k8sApiStatusEntity = new K8sApiStatusEntity();
    session = sessionFactory.openSession();
    Transaction trx = session.beginTransaction();

    createEnvironment(envName, 0);
    EnvironmentEntity envEntity = envDao.getEnvironmentFromName(envName);

    createComponentType();
    createComponent();
    ComponentEntity parentComponentEntity = session.get(ComponentEntity.class, compID);
    createComponent();
    ComponentEntity componentEntity = session.get(ComponentEntity.class, compID);
    componentEntity.setParentComponent(parentComponentEntity);
    parentCompID++;
    session.save(componentEntity);
    k8sApiStatusEntity.setComponent(componentEntity);
    k8sApiStatusEntity.setEnvironment(envEntity);
    k8sApiStatusEntity.setDeltaValue(1);
    k8sApiStatusEntity.setTotalApi(1);
    long date = System.currentTimeMillis();
    k8sApiStatusEntity.setStatusDate(new java.sql.Date(date));
    k8sApiStatusID++;
    trx.commit();
    session.close();

    return k8sApiStatusEntity;

}
 
源代码7 项目: cacheonix-core   文件: EagerKeyManyToOneTest.java
public void testLoadEntityWithEagerFetchingToKeyManyToOneReferenceBackToSelfFailureExpected() {
	// long winded method name to say that this is a test specifically for HHH-2277 ;)
	// essentially we have a bidirectional association where one side of the
	// association is actually part of a composite PK.
	//
	// The way these are mapped causes the problem because both sides
	// are defined as eager which leads to the infinite loop; if only
	// one side is marked as eager, then all is ok.  In other words the
	// problem arises when both pieces of instance data are coming from
	// the same result set.  This is because no "entry" can be placed
	// into the persistence context for the association with the
	// composite key because we are in the process of trying to build
	// the composite-id instance
	Session s = openSession();
	s.beginTransaction();
	Customer cust = new Customer( "Acme, Inc." );
	Order order = new Order( new Order.Id( cust, 1 ) );
	cust.getOrders().add( order );
	s.save( cust );
	s.getTransaction().commit();
	s.close();

	s = openSession();
	s.beginTransaction();
	try {
		cust = ( Customer ) s.get( Customer.class, cust.getId() );
	}
	catch( OverflowCondition overflow ) {
		fail( "get()/load() caused overflow condition" );
	}
	s.delete( cust );
	s.getTransaction().commit();
	s.close();
}
 
源代码8 项目: maven-framework-project   文件: Main.java
private static Employee read(Long id) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	Employee employee = (Employee) session.get(Employee.class, id);
	session.close();
	return employee;
}
 
源代码9 项目: icure-backend   文件: DrugsDAOImpl.java
public List<Mp> getMpsWithAtc(Atc atc) {
	Session sess = getSessionFactory().getCurrentSession();

	Set<Mp> mps = new HashSet<>();
	if (atc != null && atc.getCode() != null)
		for (Atc a : (List<Atc>) sess.createCriteria(Atc.class).add(Restrictions.eq("code", atc.getCode())).add(Restrictions.eq("current", true)).list()) {
			if (a.getId().getLang().equals(atc.getId().getLang())) {
				Mpp mpp = (Mpp) sess.get(Mpp.class, new MppId(a.getId().getMppId(), a.getId().getLang()));
				if (mpp != null && mpp.getRrsstate() != null && (mpp.getRrsstate().equals("G") || mpp.getRrsstate().equals("C") || mpp.getRrsstate().equals("B"))) {
					mps.add(mpp.getMp());
				}
			}
		}
	return new ArrayList<>(mps);
}
 
源代码10 项目: J2Cache   文件: J2CacheProviderTester.java
@Test
public void testQuery() {
    Session session = sessionFactory.openSession();
    User user = (User) session.get(User.class, 1);
    assertTrue(user.getId() == 1);
    user = (User) session.get(User.class, 1);
    assertTrue(user.getName().equals("tom"));
}
 
public void execute() {
	Session s = getFactory().openSession();
	Transaction t = s.beginTransaction();
	Owner o = new Owner();
	Document doc = new Document();
	Folder fol = new Folder();
	o.setName("gavin");
	doc.setName("Hibernate in Action");
	doc.setSummary("blah");
	doc.updateText("blah blah");
	fol.setName("books");
	doc.setOwner(o);
	doc.setFolder(fol);
	fol.getDocuments().add(doc);
	Assert.assertTrue( Hibernate.isPropertyInitialized( doc, "summary" ) );
	s.persist(o);
	s.persist(fol);
	t.commit();
	s.close();

	s = getFactory().openSession();
	t = s.beginTransaction();
	doc = (Document) s.get( Document.class, doc.getId() );
	Assert.assertFalse( Hibernate.isPropertyInitialized( doc, "summary" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( doc, "upperCaseName" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( doc, "owner" ) );
	s.delete(doc);
	s.delete( doc.getOwner() );
	s.delete( doc.getFolder() );
	t.commit();
	s.close();
}
 
源代码12 项目: cacheonix-core   文件: ExtraLazyTest.java
public void testOrphanDelete() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	User gavin = new User("gavin", "secret");
	Document hia = new Document("HiA", "blah blah blah", gavin);
	Document hia2 = new Document("HiA2", "blah blah blah blah", gavin);
	s.persist(gavin);
	t.commit();
	s.close();
	
	s = openSession();
	t = s.beginTransaction();
	gavin = (User) s.get(User.class, "gavin");
	assertEquals( 2, gavin.getDocuments().size() );
	gavin.getDocuments().remove(hia2);
	assertFalse( gavin.getDocuments().contains(hia2) );
	assertTrue( gavin.getDocuments().contains(hia) );
	assertEquals( 1, gavin.getDocuments().size() );
	assertFalse( Hibernate.isInitialized( gavin.getDocuments() ) );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	gavin = (User) s.get(User.class, "gavin");
	assertEquals( 1, gavin.getDocuments().size() );
	assertFalse( gavin.getDocuments().contains(hia2) );
	assertTrue( gavin.getDocuments().contains(hia) );
	assertFalse( Hibernate.isInitialized( gavin.getDocuments() ) );
	assertNull( s.get(Document.class, "HiA2") );
	gavin.getDocuments().clear();
	assertTrue( Hibernate.isInitialized( gavin.getDocuments() ) );
	s.delete(gavin);
	t.commit();
	s.close();
}
 
public void execute() {
	Session s = getFactory().openSession();
	s.beginTransaction();
	Problematic p = new Problematic();
	p.setName( "whatever" );
	p.setBytes( new byte[] { 1, 0, 1, 1, 0 } );
	s.save( p );
	s.getTransaction().commit();
	s.close();

	// this access should be ok because p1 is not a lazy proxy 
	s = getFactory().openSession();
	s.beginTransaction();
	Problematic p1 = (Problematic) s.get( Problematic.class, p.getId() );
	Assert.assertTrue( FieldInterceptionHelper.isInstrumented( p1 ) );
	p1.getRepresentation();
	s.getTransaction().commit();
	s.close();
	
	s = getFactory().openSession();
	s.beginTransaction();
	p1 = (Problematic) s.createQuery( "from Problematic" ).setReadOnly(true ).list().get( 0 );
	p1.getRepresentation();
	s.getTransaction().commit();
	s.close();
	
	s = getFactory().openSession();
	s.beginTransaction();
	p1 = (Problematic) s.load( Problematic.class, p.getId() );
	Assert.assertFalse( FieldInterceptionHelper.isInstrumented( p1 ) );
	p1.setRepresentation( p.getRepresentation() );
	s.getTransaction().commit();
	s.close();
}
 
源代码14 项目: cacheonix-core   文件: CollectionTest.java
public void testExtraLazy() throws HibernateException, SQLException {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	User u = new User( "gavin" );
	u.getPermissions().add( new Permission( "obnoxiousness" ) );
	u.getPermissions().add( new Permission( "pigheadedness" ) );
	u.getSessionData().put( "foo", "foo value" );
	s.persist( u );
	t.commit();
	s.close();
	s = openSession();
	t = s.beginTransaction();
	u = ( User ) s.get( User.class, "gavin" );

	assertFalse( Hibernate.isInitialized( u.getPermissions() ) );
	assertEquals( u.getPermissions().size(), 2 );
	assertTrue( u.getPermissions().contains( new Permission( "obnoxiousness" ) ) );
	assertFalse( u.getPermissions().contains( new Permission( "silliness" ) ) );
	assertNotNull( u.getPermissions().get( 1 ) );
	assertNull( u.getPermissions().get( 3 ) );
	assertFalse( Hibernate.isInitialized( u.getPermissions() ) );

	assertFalse( Hibernate.isInitialized( u.getSessionData() ) );
	assertEquals( u.getSessionData().size(), 1 );
	assertTrue( u.getSessionData().containsKey( "foo" ) );
	assertFalse( u.getSessionData().containsKey( "bar" ) );
	assertTrue( u.getSessionData().containsValue( "foo value" ) );
	assertFalse( u.getSessionData().containsValue( "bar" ) );
	assertEquals( "foo value", u.getSessionData().get( "foo" ) );
	assertNull( u.getSessionData().get( "bar" ) );
	assertFalse( Hibernate.isInitialized( u.getSessionData() ) );

	assertFalse( Hibernate.isInitialized( u.getSessionData() ) );
	u.getSessionData().put( "bar", "bar value" );
	u.getSessionAttributeNames().add( "bar" );
	assertFalse( Hibernate.isInitialized( u.getSessionAttributeNames() ) );
	assertTrue( Hibernate.isInitialized( u.getSessionData() ) );

	s.delete( u );
	t.commit();
	s.close();
}
 
public void execute() {
	Session s = getFactory().openSession();
	Transaction t = s.beginTransaction();
	Entity root = new Entity( "root" );
	Entity child1 = new Entity( "child1" );
	Entity child2 = new Entity( "child2" );
	root.setChild( child1 );
	child1.setSibling( child2 );
	Entity gChild1 = new Entity( "grandchild 1" );
	Entity gChild2 = new Entity( "grandchild 2" );
	child1.setChild( gChild1 );
	gChild1.setSibling( gChild2 );
	s.save( root );
	t.commit();
	s.close();

	// NOTE : child is mapped with lazy="proxy"; sibling with lazy="no-proxy"...

	s = getFactory().openSession();
	t = s.beginTransaction();
	// load root
	root = ( Entity ) s.get( Entity.class, root.getId() );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "name" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "sibling" ) );
	Assert.assertTrue( Hibernate.isPropertyInitialized( root, "child" ) );

	// get a handle to the child1 proxy reference (and make certain that
	// this does not force the lazy properties of the root entity
	// to get initialized.
	child1 = root.getChild();
	Assert.assertFalse( Hibernate.isInitialized( child1 ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "name" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "sibling" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( child1, "name" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( child1, "sibling" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( child1, "child" ) );

	child1.getName();
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "name" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "sibling" ) );
	Assert.assertTrue( Hibernate.isPropertyInitialized( child1, "name" ) );
	Assert.assertTrue( Hibernate.isPropertyInitialized( child1, "sibling" ) );
	Assert.assertTrue( Hibernate.isPropertyInitialized( child1, "child" ) );

	gChild1 = child1.getChild();
	Assert.assertFalse( Hibernate.isInitialized( gChild1 ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "name" ) );
	Assert.assertFalse( Hibernate.isPropertyInitialized( root, "sibling" ) );

	s.delete( root );
	t.commit();
	s.close();
}
 
源代码16 项目: redisson   文件: CollectionTest.java
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();

    A a = new A();
    a.id = 1L;
    a.uniqueField = "1";
    B b = new B();
    b.id = 1L;
    s.save(b);
    a.bs.add(b);
    s.save(a);
    s.flush();
    s.getTransaction().commit();

    s = openSession();
    s.beginTransaction();
    A a1 = s.get(A.class, 1L);
    System.out.println("here1");
    assertThat(a1.bs).hasSize(1);
    s.getTransaction().commit();

    Assert.assertEquals(0, stats.getSecondLevelCacheStatistics("org.redisson.hibernate.CollectionTest$A.bs").getHitCount());

    s = openSession();
    s.beginTransaction();
    A a2 = s.get(A.class, 1L);
    B b2 = a2.bs.iterator().next();
    assertThat(a2.bs.size()).isEqualTo(1);
    s.getTransaction().commit();

    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("org.redisson.hibernate.CollectionTest$A.bs").getHitCount());

    stats.logSummary();
    
}
 
public void testComponentPropertyRef() {
	Person p = new Person();
	p.setIdentity( new Identity() );
	Account a = new Account();
	a.setNumber("123-12345-1236");
	a.setOwner(p);
	p.getIdentity().setName("Gavin");
	p.getIdentity().setSsn("123-12-1234");
	Session s = openSession();
	Transaction tx = s.beginTransaction();
	s.persist(p);
	s.persist(a);
	s.flush();
	s.clear();

	a = (Account) s.createQuery("from Account a left join fetch a.owner").uniqueResult();
	assertTrue( Hibernate.isInitialized( a.getOwner() ) );
	assertNotNull( a.getOwner() );
	assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
	s.clear();

	a = (Account) s.get(Account.class, "123-12345-1236");
	assertFalse( Hibernate.isInitialized( a.getOwner() ) );
	assertNotNull( a.getOwner() );
	assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
	assertTrue( Hibernate.isInitialized( a.getOwner() ) );

	s.clear();

	getSessions().evict(Account.class);
	getSessions().evict(Person.class);

	a = (Account) s.get(Account.class, "123-12345-1236");
	assertTrue( Hibernate.isInitialized( a.getOwner() ) );
	assertNotNull( a.getOwner() );
	assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
	assertTrue( Hibernate.isInitialized( a.getOwner() ) );

	s.delete( a );
	s.delete( a.getOwner() );
	tx.commit();
	s.close();
}
 
源代码18 项目: spacewalk   文件: UserFactory.java
/**
 * Looks up the UserServerPreference corresponding to the given
 * user, server, and preference label
 * @param user user who the preference corresponds to
 * @param server server that preference corresponds to
 * @param name preference label we are looking for
 * @return UserServerPreference that corresponds to the parameters
 */
public UserServerPreference lookupServerPreferenceByUserServerAndName(User user,
        Server server,
        String name) {
    UserServerPreferenceId id = new UserServerPreferenceId(user, server, name);
    Session session = HibernateFactory.getSession();
    return (UserServerPreference) session.get(UserServerPreference.class, id);
}
 
源代码19 项目: spacewalk   文件: ActionFactory.java
/**
 * Lookup a Action by their id
 * @param id the id to search for
 * @return the Action found
 */
public static Action lookupById(Long id) {
    Session session = HibernateFactory.getSession();
    return (Action)session.get(Action.class, id);
}
 
源代码20 项目: spacewalk   文件: ConfigurationFactory.java
/**
 * Finds a ConfigFileName from the database with a given id.
 * @param id The identifier for the ConfigFileName
 * @return The sought for ConfigFileName or null if not found.
 */
public static ConfigFileName lookupConfigFileNameById(Long id) {
    Session session = HibernateFactory.getSession();
    return (ConfigFileName)session.get(ConfigFileName.class, id);
}