List of usage examples for org.hibernate Session bySimpleNaturalId
<T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(Class<T> entityClass);
From source file:com.github.snd297.hibernateequals.model.EqualsTest.java
License:Apache License
@Test public void getClassEquals() throws Exception { Session sess = null; Transaction trx = null;// w w w .j a v a 2s. com try { sess = HibernateUtil.getSessionFactory().openSession(); trx = sess.beginTransaction(); GetClassCar getClassCar0 = (GetClassCar) sess.bySimpleNaturalId(GetClassCar.class) .getReference(getClassCarVin); GetClassCar getClassCar1 = new GetClassCar(getClassCarVin); assertTrue(getClassCar0 instanceof HibernateProxy); assertFalse(getClassCar1.equals(getClassCar0)); assertTrue(getClassCar0.equals(getClassCar1)); trx.commit(); } catch (Exception e) { HibernateUtil.rollbackQuietly(trx); throw e; } finally { HibernateUtil.closeQuietly(sess); } }
From source file:com.github.snd297.hibernateequals.model.EqualsTest.java
License:Apache License
@Test public void brokenEquals() throws Exception { Session sess = null; Transaction trx = null;//w w w . j av a2 s . co m try { sess = HibernateUtil.getSessionFactory().openSession(); trx = sess.beginTransaction(); BrokenEqualsCar brokenEqualsCar0 = (BrokenEqualsCar) sess.bySimpleNaturalId(BrokenEqualsCar.class) .getReference(brokenEqualsCarVin); BrokenEqualsCar brokenEqualsCar1 = new BrokenEqualsCar(brokenEqualsCarVin); assertTrue(brokenEqualsCar0 instanceof HibernateProxy); assertFalse(brokenEqualsCar1.equals(brokenEqualsCar0)); assertTrue(brokenEqualsCar0.equals(brokenEqualsCar1)); trx.commit(); } catch (Exception e) { HibernateUtil.rollbackQuietly(trx); throw e; } finally { HibernateUtil.closeQuietly(sess); } }
From source file:com.github.snd297.hibernateequals.model.EqualsTest.java
License:Apache License
@Test public void fixedEquals() throws Exception { Session sess = null; Transaction trx = null;/*from ww w .j a v a 2s.c om*/ try { sess = HibernateUtil.getSessionFactory().openSession(); trx = sess.beginTransaction(); Car car0 = (Car) sess.bySimpleNaturalId(Car.class).getReference(carVin); Car car1 = new Car(carVin); assertTrue(car0 instanceof HibernateProxy); assertTrue(car1.equals(car0)); assertTrue(car0.equals(car1)); trx.commit(); } catch (Exception e) { HibernateUtil.rollbackQuietly(trx); throw e; } finally { HibernateUtil.closeQuietly(sess); } }
From source file:com.github.snd297.hibernateequals.persistence.EqualsTest.java
License:Apache License
@Test public void brokenEqualsInitializedProxy() throws Exception { Session sess = null; Transaction trx = null;//from www .j a va 2 s. c o m try { sess = HibernateUtil.getSessionFactory().openSession(); trx = sess.beginTransaction(); BrokenEqualsCar brokenEqualsCar0 = (BrokenEqualsCar) sess.bySimpleNaturalId(BrokenEqualsCar.class) .getReference(brokenEqualsCarVin); Hibernate.initialize(brokenEqualsCar0); BrokenEqualsCar brokenEqualsCar1 = new BrokenEqualsCar(brokenEqualsCarVin); assertTrue(brokenEqualsCar0 instanceof HibernateProxy); assertFalse(brokenEqualsCar1.equals(brokenEqualsCar0)); assertTrue(brokenEqualsCar0.equals(brokenEqualsCar1)); trx.commit(); } catch (Exception e) { HibernateUtil.rollbackQuietly(trx); throw e; } finally { HibernateUtil.closeQuietly(sess); } }
From source file:es.logongas.ix3.dao.impl.GenericDAOImplHibernate.java
License:Apache License
@Override final public EntityType readByNaturalKey(DataSession dataSession, Object naturalKey) throws BusinessException { Session session = (Session) dataSession.getDataBaseSessionImpl(); try {//from ww w . j a v a 2s . c om EntityType entity = (EntityType) session.bySimpleNaturalId(getEntityMetaData().getType()) .load(naturalKey); return entity; } catch (javax.validation.ConstraintViolationException cve) { throw new BusinessException(exceptionTranslator.getBusinessMessages(cve)); } catch (org.hibernate.exception.ConstraintViolationException cve) { throw new BusinessException(exceptionTranslator.getBusinessMessages(cve)); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:es.logongas.ix3.dao.impl.GenericDAOImplHibernate.java
License:Apache License
@Override final public EntityType readOriginalByNaturalKey(DataSession dataSession, Object naturalKey) throws BusinessException { Session session = (Session) dataSession.getDataBaseSessionAlternativeImpl(); try {/*w w w.j a v a 2 s .c o m*/ session.setCacheMode(CacheMode.IGNORE); EntityType entity = (EntityType) session.bySimpleNaturalId(getEntityMetaData().getType()) .load(naturalKey); if (entity != null) { session.evict(entity); } return entity; } catch (javax.validation.ConstraintViolationException cve) { throw new BusinessException(exceptionTranslator.getBusinessMessages(cve)); } catch (org.hibernate.exception.ConstraintViolationException cve) { throw new BusinessException(exceptionTranslator.getBusinessMessages(cve)); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:onl.netfishers.netshot.RestService.java
License:Open Source License
/** * Sets the password.//from ww w.ja v a 2 s. c o m * * @param request the request * @param rsLogin the rs login * @return the user * @throws WebApplicationException the web application exception */ @PUT @Path("user/{id}") @RolesAllowed("readonly") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public User setPassword(@Context HttpServletRequest request, RsLogin rsLogin) throws WebApplicationException { logger.debug("REST password change request, username {}.", rsLogin.getUsername()); User sessionUser = (User) request.getSession().getAttribute("user"); User user; Session session = Database.getSession(); try { session.beginTransaction(); user = (User) session.bySimpleNaturalId(User.class).load(rsLogin.getUsername()); if (user == null || !user.getUsername().equals(sessionUser.getUsername()) || !user.isLocal()) { throw new NetshotBadRequestException("Invalid user.", NetshotBadRequestException.NETSHOT_INVALID_USER); } if (!user.checkPassword(rsLogin.getPassword())) { throw new NetshotBadRequestException("Invalid current password.", NetshotBadRequestException.NETSHOT_INVALID_USER); } String newPassword = rsLogin.getNewPassword(); if (newPassword.equals("")) { throw new NetshotBadRequestException("The password cannot be empty.", NetshotBadRequestException.NETSHOT_INVALID_USER); } user.setPassword(newPassword); session.save(user); session.getTransaction().commit(); return sessionUser; } catch (HibernateException e) { session.getTransaction().rollback(); logger.error("Unable to retrieve the user {}.", rsLogin.getUsername(), e); throw new NetshotBadRequestException("Unable to retrieve the user.", NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR); } finally { session.close(); } }
From source file:onl.netfishers.netshot.RestService.java
License:Open Source License
/** * Login.// w ww.j a v a 2s . co m * * @param request the request * @param rsLogin the rs login * @return the user * @throws WebApplicationException the web application exception */ @POST @PermitAll @Path("user") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public User login(@Context HttpServletRequest request, RsLogin rsLogin) throws WebApplicationException { logger.debug("REST authentication request, username {}.", rsLogin.getUsername()); User user = null; Session session = Database.getSession(); try { user = (User) session.bySimpleNaturalId(User.class).load(rsLogin.getUsername()); } catch (HibernateException e) { logger.error("Unable to retrieve the user {}.", rsLogin.getUsername(), e); throw new NetshotBadRequestException("Unable to retrieve the user.", NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR); } finally { session.close(); } if (user != null && user.isLocal()) { if (!user.checkPassword(rsLogin.getPassword())) { user = null; } } else { User remoteUser = Radius.authenticate(rsLogin.getUsername(), rsLogin.getPassword()); if (remoteUser != null && user != null) { remoteUser.setLevel(user.getLevel()); } user = remoteUser; } if (user == null) { HttpSession httpSession = request.getSession(); httpSession.invalidate(); } else { HttpSession httpSession = request.getSession(); httpSession.setAttribute("user", user); httpSession.setMaxInactiveInterval(User.MAX_IDLE_TIME); return user; } throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); }
From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java
License:Apache License
/** * @param accessType Cache access type./*from w ww . ja v a 2s .c om*/ * @throws Exception If failed. */ private void testNaturalIdCache(AccessType accessType) throws Exception { createSessionFactories(accessType); Map<String, Integer> nameToId = new HashMap<>(); try { Session ses = sesFactory1.openSession(); try { Transaction tx = ses.beginTransaction(); for (int i = 0; i < 3; i++) { String name = "name-" + i; ses.save(new Entity(i, name)); nameToId.put(name, i); } tx.commit(); } finally { ses.close(); } ses = sesFactory1.openSession(); try { for (Map.Entry<String, Integer> e : nameToId.entrySet()) ((Entity) ses.bySimpleNaturalId(Entity.class).load(e.getKey())).getId(); } finally { ses.close(); } assertNaturalIdCache(sesFactory2, nameToId, "name-100"); assertNaturalIdCache(sesFactory1, nameToId, "name-100"); if (accessType == AccessType.READ_ONLY) return; // Update naturalId. ses = sesFactory1.openSession(); try { Transaction tx = ses.beginTransaction(); Entity e1 = (Entity) ses.load(Entity.class, 1); nameToId.remove(e1.getName()); e1.setName("name-1-changed1"); nameToId.put(e1.getName(), e1.getId()); tx.commit(); } finally { ses.close(); } assertNaturalIdCache(sesFactory2, nameToId, "name-1"); assertNaturalIdCache(sesFactory1, nameToId, "name-1"); // Update entity using another SessionFactory. ses = sesFactory2.openSession(); try { Transaction tx = ses.beginTransaction(); Entity e1 = (Entity) ses.load(Entity.class, 1); nameToId.remove(e1.getName()); e1.setName("name-1-changed2"); nameToId.put(e1.getName(), e1.getId()); tx.commit(); } finally { ses.close(); } assertNaturalIdCache(sesFactory2, nameToId, "name-1-changed1"); assertNaturalIdCache(sesFactory1, nameToId, "name-1-changed1"); // Try invalid NaturalId update. ses = sesFactory1.openSession(); Transaction tx = ses.beginTransaction(); try { Entity e1 = (Entity) ses.load(Entity.class, 1); e1.setName("name-0"); // Invalid update (duplicated name). tx.commit(); fail("Commit must fail."); } catch (ConstraintViolationException e) { log.info("Expected exception: " + e); tx.rollback(); } finally { ses.close(); } assertNaturalIdCache(sesFactory2, nameToId); assertNaturalIdCache(sesFactory1, nameToId); // Delete entity. ses = sesFactory2.openSession(); try { tx = ses.beginTransaction(); Entity e2 = (Entity) ses.load(Entity.class, 2); ses.delete(e2); nameToId.remove(e2.getName()); tx.commit(); } finally { ses.close(); } assertNaturalIdCache(sesFactory2, nameToId, "name-2"); assertNaturalIdCache(sesFactory1, nameToId, "name-2"); } finally { cleanup(); } }
From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java
License:Apache License
/** * @param sesFactory Session factory./*w w w. ja v a 2s .c o m*/ * @param nameToId Name-ID mapping. * @param absentNames Absent entities' names. */ private void assertNaturalIdCache(SessionFactory sesFactory, Map<String, Integer> nameToId, String... absentNames) { sesFactory.getStatistics().clear(); NaturalIdCacheStatistics stats = sesFactory.getStatistics().getNaturalIdCacheStatistics(NATURAL_ID_REGION); long hitBefore = stats.getHitCount(); long missBefore = stats.getMissCount(); final Session ses = sesFactory.openSession(); try { for (Map.Entry<String, Integer> e : nameToId.entrySet()) assertEquals((int) e.getValue(), ((Entity) ses.bySimpleNaturalId(Entity.class).load(e.getKey())).getId()); for (String name : absentNames) assertNull((ses.bySimpleNaturalId(Entity.class).load(name))); assertEquals(nameToId.size() + hitBefore, stats.getHitCount()); assertEquals(absentNames.length + missBefore, stats.getMissCount()); } finally { ses.close(); } }