下面列出了org.hibernate.Session#refresh ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void givenNewItemPrice_whenCriteriaUpdate_thenReturnAffectedResult() {
int oldPrice = 10, newPrice = 20;
Session session = HibernateUtil.getHibernateSession();
Item item = new Item(12, "Test Item 12", "This is a description");
item.setItemPrice(oldPrice);
session.save(item);
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaUpdate<Item> criteriaUpdate = cb.createCriteriaUpdate(Item.class);
Root<Item> root = criteriaUpdate.from(Item.class);
criteriaUpdate.set("itemPrice", newPrice);
criteriaUpdate.where(cb.equal(root.get("itemPrice"), oldPrice));
Transaction transaction = session.beginTransaction();
session.createQuery(criteriaUpdate).executeUpdate();
transaction.commit();
Item updatedItem = session.createQuery("FROM Item WHERE itemPrice = " + newPrice, Item.class).getSingleResult();
session.refresh(updatedItem);
assertEquals(newPrice, updatedItem.getItemPrice().intValue());
}
@Test // SPR-16956
@Transactional(readOnly = true)
public void findSamWithReadOnlySession() {
Person sam = personService.findByName(SAM);
sam.setName("Vlad");
// By setting setDefaultReadOnly(true), the user can no longer modify any entity...
Session session = sessionFactory.getCurrentSession();
session.flush();
session.refresh(sam);
assertEquals("Sam", sam.getName());
}
@Test // SPR-16956
@Transactional(readOnly = true)
public void findSamWithReadOnlySession() {
Person sam = personService.findByName(SAM);
sam.setName("Vlad");
// By setting setDefaultReadOnly(true), the user can no longer modify any entity...
Session session = sessionFactory.getCurrentSession();
session.flush();
session.refresh(sam);
assertEquals("Sam", sam.getName());
}
public void testRefreshCascade() throws Throwable {
Session session = openSession();
Transaction txn = session.beginTransaction();
JobBatch batch = new JobBatch( new Date() );
batch.createJob().setProcessingInstructions( "Just do it!" );
batch.createJob().setProcessingInstructions( "I know you can do it!" );
// write the stuff to the database; at this stage all job.status values are zero
session.persist( batch );
session.flush();
// behind the session's back, let's modify the statuses
updateStatuses( session.connection() );
// Now lets refresh the persistent batch, and see if the refresh cascaded to the jobs collection elements
session.refresh( batch );
Iterator itr = batch.getJobs().iterator();
while( itr.hasNext() ) {
Job job = ( Job ) itr.next();
assertEquals( "Jobs not refreshed!", 1, job.getStatus() );
}
txn.rollback();
session.close();
}
@Override
@Transactional
public void deleteSubmission(String submissionId) {
Session session = sessionFactory.getCurrentSession();
AssignmentSubmission submission = (AssignmentSubmission) session.get(AssignmentSubmission.class, submissionId);
if (submission != null) {
log.info("Deleting submission {}", submission);
Assignment assignment = submission.getAssignment();
// must call refresh here to ensure the collections are initialized before changing, this is due to lazy loaded entities
session.refresh(assignment);
assignment.getSubmissions().remove(submission);
session.update(assignment);
session.flush();
}
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Override
@Transactional
public void deleteSubmission(String submissionId) {
Session session = sessionFactory.getCurrentSession();
AssignmentSubmission submission = (AssignmentSubmission) session.get(AssignmentSubmission.class, submissionId);
if (submission != null) {
log.info("Deleting submission {}", submission);
Assignment assignment = submission.getAssignment();
// must call refresh here to ensure the collections are initialized before changing, this is due to lazy loaded entities
session.refresh(assignment);
assignment.getSubmissions().remove(submission);
session.update(assignment);
session.flush();
}
}
/**
* Erase role.
*
* @param aRole
* the a role
* @throws EMFUserError
* the EMF user error
* @see it.eng.spagobi.commons.dao.IRoleDAO#eraseRole(it.eng.spagobi.commons.bo.Role)
*/
@Override
public void eraseRole(Role aRole) throws EMFUserError {
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
SbiExtRoles hibRole = (SbiExtRoles) aSession.load(SbiExtRoles.class, aRole.getId());
// deletes associations with events (and events themselves, if they
// have no more associations)
// Query hibQuery =
// aSession.createQuery(" from SbiEventRole ser where
// ser.id.role.extRoleId = "
// + hibRole.getExtRoleId().toString());
// Query hibQuery = aSession.createQuery(" from SbiEventRole ser where ser.id.role.extRoleId = ?");
// hibQuery.setInteger(0, hibRole.getExtRoleId().intValue());
// List eventsRole = hibQuery.list();
// Iterator it = eventsRole.iterator();
// while (it.hasNext()) {
// SbiEventRole eventRole = (SbiEventRole) it.next();
// SbiEventsLog event = eventRole.getId().getEvent();
// aSession.delete(eventRole);
// aSession.flush();
// aSession.refresh(event);
// Set roles = event.getRoles();
// if (roles.isEmpty()) {
// aSession.delete(event);
// }
// }
Set<SbiAuthorizationsRoles> authorizations = hibRole.getSbiAuthorizationsRoleses();
Iterator itf = authorizations.iterator();
while (itf.hasNext()) {
SbiAuthorizationsRoles fr = (SbiAuthorizationsRoles) itf.next();
aSession.delete(fr);
aSession.flush();
aSession.refresh(hibRole);
}
aSession.delete(hibRole);
tx.commit();
} catch (HibernateException he) {
logException(he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen()) {
aSession.close();
logger.debug("The [eraseRole] occurs. Role cache will be cleaned.");
this.clearCache();
}
}
}
}
public void testIt() {
// Test saving these dyna-proxies
Session session = openSession();
session.beginTransaction();
Company company = ProxyHelper.newCompanyProxy();
company.setName( "acme" );
session.save( company );
Customer customer = ProxyHelper.newCustomerProxy();
customer.setName( "Steve" );
customer.setCompany( company );
session.save( customer );
session.getTransaction().commit();
session.close();
assertNotNull( "company id not assigned", company.getId() );
assertNotNull( "customer id not assigned", customer.getId() );
// Test loading these dyna-proxies, along with flush processing
session = openSession();
session.beginTransaction();
customer = ( Customer ) session.load( Customer.class, customer.getId() );
assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer ) );
customer.setName( "other" );
session.flush();
assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer.getCompany() ) );
session.refresh( customer );
assertEquals( "name not updated", "other", customer.getName() );
assertEquals( "company association not correct", "acme", customer.getCompany().getName() );
session.getTransaction().commit();
session.close();
// Test detached entity re-attachment with these dyna-proxies
customer.setName( "Steve" );
session = openSession();
session.beginTransaction();
session.update( customer );
session.flush();
session.refresh( customer );
assertEquals( "name not updated", "Steve", customer.getName() );
session.getTransaction().commit();
session.close();
// Test querying
session = openSession();
session.beginTransaction();
int count = session.createQuery( "from Customer" ).list().size();
assertEquals( "querying dynamic entity", 1, count );
session.clear();
count = session.createQuery( "from Person" ).list().size();
assertEquals( "querying dynamic entity", 1, count );
session.getTransaction().commit();
session.close();
// test deleteing
session = openSession();
session.beginTransaction();
session.delete( company );
session.delete( customer );
session.getTransaction().commit();
session.close();
}
public void testIt() {
// Test saving these dyna-proxies
Session session = openSession();
session.beginTransaction();
Company company = ProxyHelper.newCompanyProxy();
company.setName( "acme" );
session.save( company );
Customer customer = ProxyHelper.newCustomerProxy();
customer.setName( "Steve" );
customer.setCompany( company );
Address address = ProxyHelper.newAddressProxy();
address.setStreet( "somewhere over the rainbow" );
address.setCity( "lawerence, kansas" );
address.setPostalCode( "toto");
customer.setAddress( address );
customer.setFamily( new HashSet() );
Person son = ProxyHelper.newPersonProxy();
son.setName( "son" );
customer.getFamily().add( son );
Person wife = ProxyHelper.newPersonProxy();
wife.setName( "wife" );
customer.getFamily().add( wife );
session.save( customer );
session.getTransaction().commit();
session.close();
assertNotNull( "company id not assigned", company.getId() );
assertNotNull( "customer id not assigned", customer.getId() );
assertNotNull( "address id not assigned", address.getId() );
assertNotNull( "son:Person id not assigned", son.getId() );
assertNotNull( "wife:Person id not assigned", wife.getId() );
// Test loading these dyna-proxies, along with flush processing
session = openSession();
session.beginTransaction();
customer = ( Customer ) session.load( Customer.class, customer.getId() );
assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer ) );
customer.setName( "other" );
session.flush();
assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer.getCompany() ) );
session.refresh( customer );
assertEquals( "name not updated", "other", customer.getName() );
assertEquals( "company association not correct", "acme", customer.getCompany().getName() );
session.getTransaction().commit();
session.close();
// Test detached entity re-attachment with these dyna-proxies
customer.setName( "Steve" );
session = openSession();
session.beginTransaction();
session.update( customer );
session.flush();
session.refresh( customer );
assertEquals( "name not updated", "Steve", customer.getName() );
session.getTransaction().commit();
session.close();
// Test querying
session = openSession();
session.beginTransaction();
int count = session.createQuery( "from Customer" ).list().size();
assertEquals( "querying dynamic entity", 1, count );
session.clear();
count = session.createQuery( "from Person" ).list().size();
assertEquals( "querying dynamic entity", 3, count );
session.getTransaction().commit();
session.close();
// test deleteing
session = openSession();
session.beginTransaction();
session.delete( company );
session.delete( customer );
session.getTransaction().commit();
session.close();
}
/**
* Update the instructional offering config
* @param request
* @param frm
*/
private void doUpdate(HttpServletRequest request, InstructionalOfferingModifyForm frm)
throws Exception {
// Get Instructional Offering Config
InstrOfferingConfigDAO iocdao = new InstrOfferingConfigDAO();
InstrOfferingConfig ioc = iocdao.get(frm.getInstrOffrConfigId());
Session hibSession = iocdao.getSession();
// Get default room group
RoomGroup rg = RoomGroup.getGlobalDefaultRoomGroup(ioc.getSession());
sessionContext.checkPermission(ioc, Right.MultipleClassSetup);
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
// If the instructional offering config limit or unlimited flag has changed update it.
if (frm.isInstrOffrConfigUnlimited() != ioc.isUnlimitedEnrollment()) {
ioc.setUnlimitedEnrollment(frm.isInstrOffrConfigUnlimited());
ioc.setLimit(frm.isInstrOffrConfigUnlimited() ? 0 : frm.getInstrOffrConfigLimit());
hibSession.update(ioc);
} else if (!frm.getInstrOffrConfigLimit().equals(ioc.getLimit())) {
ioc.setLimit(frm.getInstrOffrConfigLimit());
hibSession.update(ioc);
}
InstructionalMethod imeth = (frm.getInstructionalMethod() == null || frm.getInstructionalMethod() < 0 ? null : InstructionalMethodDAO.getInstance().get(frm.getInstructionalMethod(), hibSession));
if (!ToolBox.equals(ioc.getInstructionalMethod(), imeth)) {
ioc.setInstructionalMethod(imeth);
hibSession.update(ioc);
}
// Get map of subpart ownership so that after the classes have changed it is possible to see if the ownership for a subparts has changed
HashMap origSubpartManagingDept = new HashMap();
if (ioc.getSchedulingSubparts() != null){
SchedulingSubpart ss = null;
for (Iterator it = ioc.getSchedulingSubparts().iterator(); it.hasNext();){
ss = (SchedulingSubpart) it.next();
origSubpartManagingDept.put(ss.getUniqueId(), ss.getManagingDept());
}
}
// For all added classes, create the classes and save them, get back a map of the temp ids to the new classes
HashMap tmpClassIdsToClasses = addClasses(frm, ioc, hibSession);
// For all changed classes, update them
modifyClasses(frm, ioc, hibSession, rg, tmpClassIdsToClasses);
// Update subpart ownership
modifySubparts(ioc, origSubpartManagingDept, rg, hibSession);
// Delete all classes in the original classes that are no longer in the modified classes
deleteClasses(frm, ioc, hibSession, tmpClassIdsToClasses);
String className = ApplicationProperty.ExternalActionInstrOffrConfigChange.value();
ExternalInstrOffrConfigChangeAction configChangeAction = null;
if (className != null && className.trim().length() > 0){
configChangeAction = (ExternalInstrOffrConfigChangeAction) (Class.forName(className).newInstance());
if (!configChangeAction.validateConfigChangeCanOccur(ioc.getInstructionalOffering(), hibSession)){
throw new Exception("Configuration change violates rules for Add On, rolling back the change.");
}
}
ioc.getInstructionalOffering().computeLabels(hibSession);
ChangeLog.addChange(
hibSession,
sessionContext,
ioc,
ChangeLog.Source.CLASS_SETUP,
ChangeLog.Operation.UPDATE,
ioc.getInstructionalOffering().getControllingCourseOffering().getSubjectArea(),
null);
tx.commit();
hibSession.flush();
hibSession.refresh(ioc);
hibSession.refresh(ioc.getInstructionalOffering());
if (configChangeAction != null){
configChangeAction.performExternalInstrOffrConfigChangeAction(ioc.getInstructionalOffering(), hibSession);
}
}
catch (Exception e) {
Debug.error(e);
try {
if(tx!=null && tx.isActive())
tx.rollback();
}
catch (Exception e1) { }
throw e;
}
}
/**
* Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
* long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
*/
public void refresh(T obj, Session s) {
s.refresh(obj);
}