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

The following are Jave code examples for showing how to use get() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ImageClassify   File: CategoryService.java   View Source Code Vote up 6 votes
/**
 * 根据类别id找到类别对象
 */
@Override
public Category findCategoryById(int category_id) {
	Category category = null;
	Session session = HibernateUtils.getSession();// 生成Session实例
	Transaction tx = session.beginTransaction();// 生成事务实例
	try {
		category = (Category) session.get(Category.class, category_id);
		tx.commit();// 提交事务
		// 调用session的get()方法,找到此用户到内存中
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();// 事务回滚
	} finally {
		HibernateUtils.closeSession();// 关闭session实例
	}
	return category;
}
 
Example 2
Project: ImageClassify   File: OauthService.java   View Source Code Vote up 6 votes
/**
 * 依据oauth_id找到Oauth对象并返回此对象
 */
@Override
public Oauth findOauthByOauthId(int oauth_id) {
	 Oauth oauth = null;
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 try {
	     oauth =  (Oauth) session.get(Oauth.class, oauth_id);
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}
	 return oauth;
}
 
Example 3
Project: uflo   File: GetProcessInstanceVariableCommand.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
private Variable getVariable(Context context,ProcessInstance pi) {
	Session session=context.getSession();
	Criteria criteria=session.createCriteria(Variable.class).add(Restrictions.eq("processInstanceId", pi.getId())).add(Restrictions.eq("key", key));;
	List<Variable> vars=criteria.list();
	if(vars.size()==0){
		if(pi.getParentId()>0){
			ProcessInstance parentInstance=(ProcessInstance)session.get(ProcessInstance.class,pi.getParentId());
			return getVariable(context, parentInstance);
		}else{
			return null;
		}
	}else{
		for(Variable var:vars){
			if(var instanceof BlobVariable){
				((BlobVariable)var).initValue(context);
			}
			if(var instanceof TextVariable){
				((TextVariable)var).initValue(context);
			}
		}
		return vars.get(0);
	}
}
 
Example 4
Project: Celebino   File: GenericDao.java   View Source Code Vote up 6 votes
@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;
}
 
Example 5
Project: Learning-Spring-5.0   File: BookDAO_SessionFactory.java   View Source Code Vote up 6 votes
@Override
public int updateBook(long ISBN, int price) {
	// TODO Auto-generated method stub

	Session session = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	try {
		Book book = session.get(Book.class, ISBN);
		book.setPrice(price);

		session.saveOrUpdate(book);
		transaction.commit();
		session.close();
		return 1;
	} catch (DataAccessException exception) {
		exception.printStackTrace();
	}
	return 0;

}
 
Example 6
Project: docker-restful-java   File: UserController.java   View Source Code Vote up 5 votes
/**
 * Http requet which get a specific
 * user depending on the id.
 *
 * @param id user id
 * @return a response which contains the user or errors.
 */
@GET
@Path("{id}/")
public Response show(@PathParam("id") Long id) {
    LOGGER.info("#GET {" + id + "} ");
    Response response = null;
    if (this.authorization) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            User user = session.get(User.class, id);
            session.getTransaction().commit();
            session.close();

            if (user == null) {
                response = Error.notFound(String.valueOf(id))
                        .getResponse();
                LOGGER.warning("#GET {" + id + "} " + response.toString());
            } else {
                response = Response
                        .ok(user)
                        .build();
                LOGGER.info("#GET {" + id + "} " + response.toString());
            }

        } catch (Exception exception) {
            response = Error.internalServer(exception)
                    .getResponse();
            LOGGER.warning("#GET {" + id + "} " + exception.getLocalizedMessage());
            session.getTransaction().rollback();
        }
    } else {
        response = this.getUnauthorization();
    }
    return response;
}
 
Example 7
Project: ByteJTA-sample   File: AccountDaoImpl.java   View Source Code Vote up 5 votes
public Account findById(String identifier) {
	Session session = null;
	try {
		session = this.sessionFactory.openSession();
		return (Account) session.get(Account.class, identifier);
	} finally {
		this.closeSessionIfNecessary(session);
	}
}
 
Example 8
Project: NewsSystem   File: NewsInfoDAOImpl.java   View Source Code Vote up 5 votes
/**
 * 根据id取得记录
 */
@Override
public NewsInfo getNewsInfoById(int id) {
	Session session = SessionFactory.getCurrentSession();
	NewsInfo newsInfo = (NewsInfo) session.get(NewsInfo.class, id);
	return newsInfo;
}
 
Example 9
Project: Hibernate_Association_Mapping_ManyToOne_Save_Load_Maven   File: MTO_DAOImpl.java   View Source Code Vote up 5 votes
@Override
public void addingNewChildToExistingParent() {
	Session ses=null;
	Department dept=null;
	Employee emp=null;
	Transaction tx=null;
	//PhoneNumber ph3=null;
   //get Session
	ses=HibernateUtil.getSession();
	//Load parent object(Existing)
	dept=ses.get(Department.class,1001);
	//child objs
	 	emp=new Employee();
	 	emp.setEname("Amit");
	 	emp.setEsal(60000f);
	 	//set to existing dept
	 emp.setDept(dept);

	try{
		tx=ses.beginTransaction();
		 int idval=(Integer)ses.save(emp);
		tx.commit();
		System.out.println("new Employee is added to existing Department: "+idval);
	}//try
	catch(Exception e){
		tx.rollback();
	}
}
 
Example 10
Project: training-sample   File: HibernateOrderDao.java   View Source Code Vote up 5 votes
@Override
public User findByPrimary(Long id) {
	User user = null;
	Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();
		user = session.get(User.class, id);
		session.getTransaction().commit();
	} catch (RuntimeException e) {
		session.getTransaction().rollback();
	}
	return user;
}
 
Example 11
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   View Source Code Vote up 5 votes
@Test
public void testUnidirectionalManyToOne() throws Exception {
	final Session session = openSession();
	Transaction transaction = session.beginTransaction();
	JUG jug = new JUG( "summer_camp" );
	jug.setName( "JUG Summer Camp" );
	session.persist( jug );
	Member emmanuel = new Member( "emmanuel" );
	emmanuel.setName( "Emmanuel Bernard" );
	emmanuel.setMemberOf( jug );
	Member jerome = new Member( "jerome" );
	jerome.setName( "Jerome" );
	jerome.setMemberOf( jug );
	session.persist( emmanuel );
	session.persist( jerome );
	session.flush();
	transaction.commit();
	assertThat( getNumberOfEntities( sessionFactory ) ).isEqualTo( 3 );
	assertThat( getNumberOfAssociations( sessionFactory ) ).isEqualTo( 0 );

	session.clear();

	transaction = session.beginTransaction();
	emmanuel = session.get( Member.class, emmanuel.getId() );
	jug = emmanuel.getMemberOf();
	session.delete( emmanuel );
	jerome = session.get( Member.class, jerome.getId() );
	session.delete( jerome );
	session.delete( jug );
	transaction.commit();
	assertThat( getNumberOfEntities( sessionFactory ) ).isEqualTo( 0 );
	assertThat( getNumberOfAssociations( sessionFactory ) ).isEqualTo( 0 );

	session.close();

	checkCleanCache();
}
 
Example 12
Project: hska-vis-legacy   File: GenericHibernateDAO.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public E getObjectById(PK id) {
			
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    
    session.beginTransaction();

    E entity = (E) session.get(entityClass, id);
    session.getTransaction().commit();
    return (E) entity;
}
 
Example 13
Project: hibernate-ogm-redis   File: RedisPerformanceTest.java   View Source Code Vote up 4 votes
@Test
@BMRules(rules = {
		@BMRule(targetClass = "org.hibernate.ogm.datastore.redis.impl.json.JsonEntityStorageStrategy",
				targetMethod = "storeEntity(java.lang.String, org.hibernate.ogm.datastore.redis.dialect.value.Entity)",
				helper = "org.hibernate.ogm.utils.BytemanHelper",
				action = "countInvocation(\"storeEntity\")",
				name = "countStoreEntity"),
		@BMRule(targetClass = "org.hibernate.ogm.datastore.redis.impl.json.JsonEntityStorageStrategy",
				targetMethod = "getEntity(java.lang.String)",
				helper = "org.hibernate.ogm.utils.BytemanHelper",
				action = "countInvocation(\"getEntity\")",
				name = "countGetEntity")
})
public void testNumberOfCallsToDatastore() throws Exception {
	//insert entity with embedded collection
	Session session = openSession();
	Transaction tx = session.beginTransaction();
	GrandChild luke = new GrandChild();
	luke.setName( "Luke" );
	GrandChild leia = new GrandChild();
	leia.setName( "Leia" );
	GrandMother grandMother = new GrandMother();
	grandMother.getGrandChildren().add( luke );
	grandMother.getGrandChildren().add( leia );
	session.persist( grandMother );
	tx.commit();

	session.clear();

	int getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	int storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 1 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 1 );

	// Check that all the counters have been reset to 0
	getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 0 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 0 );

	// Remove one of the elements
	tx = session.beginTransaction();
	grandMother = (GrandMother) session.get( GrandMother.class, grandMother.getId() );
	grandMother.getGrandChildren().remove( 0 );
	tx.commit();
	session.clear();

	getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 1 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 1 );

	// Assert removal has been propagated
	tx = session.beginTransaction();
	grandMother = (GrandMother) session.get( GrandMother.class, grandMother.getId() );
	assertThat( grandMother.getGrandChildren() ).onProperty( "name" ).containsExactly( "Leia" );

	session.delete( grandMother );
	tx.commit();

	session.close();
}
 
Example 14
Project: hibernate-ogm-redis   File: ManyToOneInEntityJsonRepresentationTest.java   View Source Code Vote up 4 votes
@Test
public void testDefaultBiDirManyToOneCompositeKeyTest() throws Exception {

	//given
	Session session = openSession();
	Transaction transaction = session.beginTransaction();
	Court court = new Court();
	court.setId( new Court.CourtId() );
	court.getId().setCountryCode( "DE" );
	court.getId().setSequenceNo( 123 );
	court.setName( "Hamburg Court" );
	session.persist( court );
	Game game1 = new Game();
	game1.setId( new Game.GameId() );
	game1.getId().setCategory( "primary" );
	game1.getId().setSequenceNo( 456 );
	game1.setName( "The game" );
	game1.setPlayedOn( court );
	court.getGames().add( game1 );
	Game game2 = new Game();
	game2.setId( new Game.GameId() );
	game2.getId().setCategory( "primary" );
	game2.getId().setSequenceNo( 457 );
	game2.setName( "The other game" );
	game2.setPlayedOn( court );
	session.persist( game1 );
	session.persist( game2 );
	session.flush();
	transaction.commit();


	// when
	String representation = new String(
			getProvider().getConnection().get(
					"Court:{\"id.countryCode\":\"DE\",\"id.sequenceNo\":123}"
			)
	);

	// then
	JSONAssert.assertEquals(
			"{\"games\":[{\"gameSequenceNo\":456,\"category\":\"primary\"}," +
					"{\"gameSequenceNo\":457,\"category\":\"primary\"}]," +
					"\"name\":\"Hamburg Court\"}",
			representation,
			JSONCompareMode.NON_EXTENSIBLE
	);


	session.clear();

	transaction = session.beginTransaction();
	Court localCourt = session.get( Court.class, new Court.CourtId( "DE", 123 ) );
	assertThat( localCourt.getGames() ).hasSize( 2 );
	for ( Game game : localCourt.getGames() ) {
		session.delete( game );
	}
	localCourt.getGames().clear();
	session.delete( localCourt );
	transaction.commit();

	session.close();
}
 
Example 15
Project: uflo   File: TextVariable.java   View Source Code Vote up 4 votes
public void initValue(Context context){
	Session session=context.getSession();
	blob=(Blob)session.get(Blob.class,blobId);
	text=(String)SerializationUtils.deserialize(blob.getBlobValue());
}
 
Example 16
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   View Source Code Vote up 4 votes
@Test
public void testDefaultBiDirManyToOneCompositeKeyTest() throws Exception {
	Session session = openSession();
	Transaction transaction = session.beginTransaction();
	Court court = new Court();
	court.setId( new Court.CourtId() );
	court.getId().setCountryCode( "DE" );
	court.getId().setSequenceNo( 123 );
	court.setName( "Hamburg Court" );
	session.persist( court );
	Game game1 = new Game();
	game1.setId( new Game.GameId() );
	game1.getId().setCategory( "primary" );
	game1.getId().setSequenceNo( 456 );
	game1.setName( "The game" );
	game1.setPlayedOn( court );
	court.getGames().add( game1 );
	Game game2 = new Game();
	game2.setId( new Game.GameId() );
	game2.getId().setCategory( "primary" );
	game2.getId().setSequenceNo( 457 );
	game2.setName( "The other game" );
	game2.setPlayedOn( court );
	session.persist( game1 );
	session.persist( game2 );
	session.flush();
	transaction.commit();

	session.clear();

	transaction = session.beginTransaction();
	Court localCourt = session.get( Court.class, new Court.CourtId( "DE", 123 ) );
	assertThat( localCourt.getGames() ).hasSize( 2 );
	for ( Game game : localCourt.getGames() ) {
		session.delete( game );
	}
	localCourt.getGames().clear();
	session.delete( localCourt );
	transaction.commit();

	session.close();
}
 
Example 17
Project: Planchester   File: PersistanceFacade.java   View Source Code Vote up 4 votes
public T get(int oid) {
    Session session = DatabaseConnectionHandler.getInstance().beginTransaction();
    T object = session.get(persistanceClass, oid);
    DatabaseConnectionHandler.getInstance().commitTransaction();
    return object;
}
 
Example 18
Project: Planchester   File: PersistanceFacade.java   View Source Code Vote up 4 votes
public void remove(int oid) {
    Session session = DatabaseConnectionHandler.getInstance().beginTransaction();
    Object obj = (T)session.get(persistanceClass, oid);
    session.delete(obj);
    DatabaseConnectionHandler.getInstance().commitTransaction();
}
 
Example 19
Project: bdf2   File: GenericTaskAssignmentHandler.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
public void assign(Assignable assignable, OpenExecution execution) throws Exception {
	String hql="from "+TaskAssignment.class.getName()+" where processDefinitionId=:processDefinitionId and taskName=:taskName";
	IBpmService bpmService=ContextHolder.getBean(IBpmService.BEAN_ID);
	String processDefinitionId=execution.getProcessDefinitionId();
	String nodeName=execution.getActivity().getName();
	Session session=bpmService.getSessionFactory().openSession();
	try{
		List<TaskAssignment> list=session.createQuery(hql).setString("processDefinitionId", processDefinitionId).setString("taskName", nodeName).list();
		if(list.size()>0){
			List<String> principals=new ArrayList<String>();
			for(TaskAssignment assignment:list){
				String assignmentDefId=assignment.getAssignmentDefId();
				AssignmentDef def=(AssignmentDef)session.get(AssignmentDef.class, assignmentDefId);
				String type=def.getType();
				for(IAssignmentProvider provider:bpmService.getApplicationContext().getBeansOfType(IAssignmentProvider.class).values()){
					if(provider.getTypeId().equals(type)){
						Collection<PrincipalDef> p=provider.getTaskPrincipals(assignmentDefId, execution);
						if(p!=null && p.size()>0){
							for(PrincipalDef principalDef:p){
								String principal=principalDef.getId();
								if(!principals.contains(principal)){
									principals.add(principal);
								}
							}
						}
					}
				}
			}
			if(principals.size()>0){
				if(principals.size()==1){
					assignable.setAssignee(principals.get(0));
				}else{
					for(String id:principals){
						assignable.addCandidateUser(id);													
					}
				}
				createReminderJob(principals,session,(TaskImpl)assignable,execution.getProcessDefinitionId());
			}else{
				throw new RuntimeException("Task node ["+nodeName+"] in process "+processDefinitionId+" was not found any principal!");					
			}
		}else{
			throw new RuntimeException("Task node ["+nodeName+"] in process "+processDefinitionId+" was not found assignment info!");
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 20
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   View Source Code Vote up 4 votes
@Test
public void testBidirectionalManyToOneRegular() throws Exception {
	final Session session = openSession();
	Transaction transaction = session.beginTransaction();
	SalesForce force = new SalesForce( "sales_force" );
	force.setCorporation( "Red Hat" );
	session.save( force );
	SalesGuy eric = new SalesGuy( "eric" );
	eric.setName( "Eric" );
	eric.setSalesForce( force );
	force.getSalesGuys().add( eric );
	session.save( eric );
	SalesGuy simon = new SalesGuy( "simon" );
	simon.setName( "Simon" );
	simon.setSalesForce( force );
	force.getSalesGuys().add( simon );
	session.save( simon );
	transaction.commit();
	session.clear();

	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertNotNull( force.getSalesGuys() );
	assertEquals( 2, force.getSalesGuys().size() );
	simon = session.get( SalesGuy.class, simon.getId() );
	// purposely faulty
	// force.getSalesGuys().remove( simon );
	session.delete( simon );
	transaction.commit();
	session.clear();

	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertNotNull( force.getSalesGuys() );
	assertEquals( 1, force.getSalesGuys().size() );
	session.delete( force.getSalesGuys().iterator().next() );
	session.delete( force );
	transaction.commit();

	session.close();

	checkCleanCache();
}