Java Code Examples for org.hibernate.Session#get()

The following examples show how to use org.hibernate.Session#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HibernateFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: ArrayTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
}
 
Example 3
Source File: J2CacheProviderTester.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 4
Source File: CRUDTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: J2CacheProviderTester.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 6
Source File: TestLazyPropertyCustomTypeExecutable.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example 7
Source File: ExtraLazyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example 8
Source File: TestIsPropertyInitializedExecutable.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example 9
Source File: UserFactory.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 10
Source File: DrugsDAOImpl.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: Main.java    From maven-framework-project with MIT License 5 votes vote down vote up
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;
}
 
Example 12
Source File: EagerKeyManyToOneTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example 13
Source File: TestDaoService.java    From kardio with Apache License 2.0 5 votes vote down vote up
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;

}
 
Example 14
Source File: CollectionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
}
 
Example 15
Source File: TestManyToOneProxyExecutable.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
}
 
Example 16
Source File: CollectionTest.java    From redisson with Apache License 2.0 4 votes vote down vote up
@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();
    
}
 
Example 17
Source File: CompleteComponentPropertyRefTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
}
 
Example 18
Source File: UserFactory.java    From spacewalk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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);
}
 
Example 19
Source File: ActionFactory.java    From spacewalk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: ConfigurationFactory.java    From spacewalk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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);
}