Java Code Examples for org.hibernate.HibernateException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project bonecp, under directory /bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/.

Source file: BoneCPConnectionProvider.java

  23 
vote

/** 
 * Creates the given connection pool with the given configuration. Extracted here to make unit mocking easier.
 * @param config configuration object.
 * @return BoneCP connection pool handle.
 */
protected BoneCP createPool(BoneCPConfig config){
  try {
    return new BoneCP(config);
  }
 catch (  SQLException e) {
    throw new HibernateException(e);
  }
}
 

Example 2

From project hibernate-dsc, under directory /src/main/java/com/corundumstudio/hibernate/dsc/.

Source file: DynamicQueryCache.java

  22 
vote

private Map<String,Object> extractValues(QueryKey key){
  try {
    Map<String,Object> paramValues=(Map<String,Object>)positionalParameterField.get(key);
    Map<String,Object> values=new HashMap<String,Object>(paramValues.size());
    for (    Map.Entry<String,Object> entry : paramValues.entrySet()) {
      TypedValue typeValue=(TypedValue)entry.getValue();
      values.put(entry.getKey(),typeValue.getValue());
    }
    return values;
  }
 catch (  Exception e) {
    throw new HibernateException(e);
  }
}
 

Example 3

From project hibernate-jpaql, under directory /hibernate-jpaql/src/main/java/org/hibernate/sql/ast/origin/hql/resolve/path/impl/.

Source file: BasicPathResolutionStrategySupport.java

  21 
vote

public HibernateTree handleTerminalPathPart(String name){
  if (CollectionProperties.isAnyCollectionProperty(name)) {
    Table joinedTable=locateOrBuildPropertyJoinedTable(lhs,propertyName,null,false,false);
    return generatePropertyColumnList(joinedTable.getTableSpace().getPersisterSpace(),name);
  }
  throw new HibernateException("cannot implicit join across a collection association");
}
 

Example 4

From project hibernate-ogm, under directory /hibernate-ogm-core/src/main/java/org/hibernate/ogm/jpa/impl/.

Source file: OgmEntityManager.java

  21 
vote

@Override public <T>T unwrap(Class<T> cls){
  final T session=hibernateEm.unwrap(cls);
  if (Session.class.isAssignableFrom(cls) || SessionImplementor.class.isAssignableFrom(cls)) {
    return (T)buildOgmSession((EventSource)session);
  }
  throw new HibernateException("Cannot unwrap the following type: " + cls);
}
 

Example 5

From project agile, under directory /agile-storage/src/main/java/org/hibernate/connection/.

Source file: DBCPConnectionProvider.java

  20 
vote

public void close() throws HibernateException {
  log.debug("Close DBCPConnectionProvider");
  try {
    if (ds != null) {
      ds.close();
      ds=null;
    }
 else {
      log.warn("Cannot close DBCP pool (not initialized)");
    }
  }
 catch (  Exception e) {
    throw new HibernateException("Could not close DBCP pool",e);
  }
  log.debug("Close DBCPConnectionProvider complete");
}
 

Example 6

From project components, under directory /bpm/src/main/java/org/switchyard/component/bpm/jta/hibernate/.

Source file: AS7TransactionManagerLookup.java

  20 
vote

private static Object jndiLookup(Properties properties,String name) throws HibernateException {
  Context ctx=null;
  try {
    ctx=properties != null ? new InitialContext(properties) : new InitialContext();
    return ctx.lookup(name);
  }
 catch (  NamingException ne) {
    LOGGER.error(ne.getMessage());
    throw new HibernateException(ne);
  }
 finally {
    if (ctx != null) {
      try {
        ctx.close();
      }
 catch (      Throwable t) {
        LOGGER.error(t.getMessage());
      }
    }
  }
}
 

Example 7

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/.

Source file: TextClobType.java

  20 
vote

/** 
 * This method tries to determine if the passed PreparedStatement is a Wrapper for an actual PreparedStatement. Database objects are often wrapped in pooling implementations to handle connection clean up, and EJB type transaction participation. We need to get at the real PreparedStatement to determin if it is an Oracle PreparedStatement that is being wrapped. This allows us to handle Oracle differently, since Oracle LOB types work differently in JDBC than all other databases.
 * @param stmt
 * @return The passed statement, or the PreparedStatement that the passed stmtis wrapping.
 * @throws HibernateException
 */
PreparedStatement getRealStatement(PreparedStatement stmt) throws HibernateException {
  Method[] methods=stmt.getClass().getMethods();
  for (int i=0; i < methods.length; i++) {
    String returnType=methods[i].getReturnType().getName();
    if (((Statement.class.getName().equals(returnType)) || (PreparedStatement.class.getName().equals(returnType))) && methods[i].getParameterTypes().length == 0) {
      Statement s=null;
      try {
        s=(Statement)methods[i].invoke(stmt,null);
      }
 catch (      SecurityException e) {
        throw new HibernateException("Security Error getting method [getDelegate] on [" + stmt.getClass().getName() + "::"+ methods[i].getName()+ "]",e);
      }
catch (      IllegalArgumentException e) {
        throw new HibernateException("Error calling method [getDelegate] on [" + stmt.getClass().getName() + "::"+ methods[i].getName()+ "]",e);
      }
catch (      IllegalAccessException e) {
        throw new HibernateException("Error calling method [getDelegate] on [" + stmt.getClass().getName() + "::"+ methods[i].getName()+ "]",e);
      }
catch (      InvocationTargetException e) {
        throw new HibernateException("Error calling method [getDelegate] on [" + stmt.getClass().getName() + "::"+ methods[i].getName()+ "]",e);
      }
      return (PreparedStatement)s;
    }
  }
  return stmt;
}
 

Example 8

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: EnumUserType.java

  19 
vote

public Object nullSafeGet(ResultSet resultSet,String[] names,Object owner) throws HibernateException, SQLException {
  String name=resultSet.getString(names[0]);
  Object result=null;
  if (!resultSet.wasNull()) {
    result=Enum.valueOf(clazz,name);
  }
  return result;
}
 

Example 9

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source file: ServletAuthMethods.java

  19 
vote

/** 
 * Sends a password reset email to a user
 * @throws DisallowedException Only an administrator can send a password reset email
 */
public synchronized static void sendPasswordReset(HttpServletRequest request,AuthManagerInfo authManager) throws DisallowedException, ObjectNotFoundException, CantDoThatException, CodingErrorException, MessagingException {
  String internalUserName=request.getParameter("internalusername");
  AppUserInfo user=authManager.getUserByInternalName(request,internalUserName);
  HibernateUtil.startHibernateTransaction();
  try {
    authManager.sendPasswordReset(request,user);
    HibernateUtil.currentSession().getTransaction().commit();
  }
 catch (  HibernateException hex) {
    HibernateUtil.rollbackHibernateTransaction();
    throw new CantDoThatException("Sending password reset failed",hex);
  }
catch (  AgileBaseException pex) {
    HibernateUtil.rollbackHibernateTransaction();
    throw new CantDoThatException(pex.getMessage(),pex);
  }
 finally {
    HibernateUtil.closeSession();
  }
}
 

Example 10

From project ATHENA, under directory /core/apa/src/main/java/org/fracturedatlas/athena/apa/impl/.

Source file: LongUserType.java

  19 
vote

public boolean equals(Object x,Object y) throws HibernateException {
  if (x == y) {
    return true;
  }
 else   if (x == null || y == null) {
    return false;
  }
 else {
    return x.equals(y);
  }
}
 

Example 11

From project baseunits, under directory /src/main/java/jp/xet/baseunits/hibernate/.

Source file: AbstractBaseunitsType.java

  19 
vote

@Override public boolean equals(Object x,Object y) throws HibernateException {
  if (x == y) {
    return true;
  }
  if (x == null || y == null) {
    return false;
  }
  return x.equals(y);
}
 

Example 12

From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/dao/hibernate/.

Source file: HibernateBookmarkStore.java

  19 
vote

/** 
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#getBookmarkSet(java.lang.String,java.lang.String)
 */
public BookmarkSet getBookmarkSet(String owner,String name){
  try {
    final Session session=this.getSession(false);
    final Criteria c=session.createCriteria(BookmarkSet.class);
    c.add(Restrictions.and(this.smartEqual(PARAM_NAME,name),this.smartEqual(PARAM_OWNER,owner)));
    c.setCacheable(true);
    final BookmarkSet bs=(BookmarkSet)c.uniqueResult();
    return bs;
  }
 catch (  HibernateException ex) {
    throw convertHibernateAccessException(ex);
  }
}
 

Example 13

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/boot/.

Source file: Bootstrapper.java

  19 
vote

public void bootstrap() throws Exception {
  logger.info("Bootstrapper executing");
  Session session=sessionFactory.openSession();
  try {
    session.createCriteria(User.class).setMaxResults(1).list();
    logger.info("Bootstrapper found schema, skipping schema creation");
  }
 catch (  HibernateException e) {
    logger.info("Bootstrapper did not find schema");
    TransactionStatus txn=transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {
      logger.info("creating schema...");
      bootstrapSchema();
      logger.info("creating default admin user...");
      bootstrapUsers();
    }
  finally {
      if (txn.isRollbackOnly()) {
        transactionManager.rollback(txn);
      }
 else {
        transactionManager.commit(txn);
      }
    }
  }
 finally {
    session.close();
  }
  logger.info("Bootstrapper execution completed");
}
 

Example 14

From project brix-cms-plugins, under directory /examples/example-springsecurity/src/main/java/brix/demo/service/impl/.

Source file: UserDAOImpl.java

  19 
vote

public GrantedAuthority getGrantedAuthorityByID(final String roleName){
  return (GrantedAuthority)getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(    Session session) throws HibernateException, SQLException {
      return session.createCriteria(Role.class).add(Restrictions.eq("roleName",roleName)).uniqueResult();
    }
  }
);
}
 

Example 15

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/dao/.

Source file: HibernateCalendarStore.java

  19 
vote

public void storeCalendarDefinition(CalendarDefinition listing){
  try {
    getHibernateTemplate().saveOrUpdate(listing);
    getHibernateTemplate().flush();
  }
 catch (  HibernateException ex) {
    throw convertHibernateAccessException(ex);
  }
}
 

Example 16

From project camel-osgi-servicemix-tutorial, under directory /persistence-hibernate/src/main/java/org/fusesource/devoxx/reportincident/dao/impl/.

Source file: IncidentDAOImpl.java

  19 
vote

public List<Incident> findIncident(String key) throws HibernateException {
  q=this.sessionFactory.getCurrentSession().createQuery(findIncidentByReference);
  q.setString("ref",key);
  List<Incident> list=q.list();
  return list;
}
 

Example 17

From project camel-osgi-tutorial, under directory /reportincident.persistence/src/main/java/org/apache/camel/example/reportincident/dao/impl/.

Source file: IncidentDAOImpl.java

  19 
vote

public List<Incident> findIncident(String key) throws HibernateException {
  q=this.sessionFactory.getCurrentSession().createQuery(findIncidentByReference);
  q.setString("ref",key);
  List<Incident> list=q.list();
  return list;
}
 

Example 18

From project candlepin, under directory /src/main/java/org/candlepin/pinsetter/tasks/.

Source file: CancelJobJob.java

  19 
vote

@Override public void execute(JobExecutionContext ctx) throws JobExecutionException {
  List<JobStatus> canceledJobs;
  try {
    canceledJobs=jobCurator.findCanceledJobs();
  }
 catch (  HibernateException e) {
    log.error("Cannot execute query: ",e);
    throw new JobExecutionException(e);
  }
  for (  JobStatus j : canceledJobs) {
    try {
      pinsetterKernel.cancelJob(j.getId(),j.getGroup());
    }
 catch (    PinsetterException e) {
      e.printStackTrace();
    }
  }
}
 

Example 19

From project caseconductor-platform, under directory /utest-persistence/src/main/java/com/utest/dao/.

Source file: AuditTrailInterceptor.java

  19 
vote

@SuppressWarnings("unchecked") @Override public void postFlush(final Iterator entities) throws CallbackException {
  final Session session=sessionFactory.openSession();
  try {
    while (!logRecords.isEmpty()) {
      final AuditRecord logRecord=logRecords.firstElement();
      logRecords.remove(logRecord);
      if (AuditRecord.INSERT.equals(logRecord.getEventId())) {
        final Integer id=getObjectId(logRecord.getEntityObject());
        if (id != null) {
          logRecord.setEntityId(getObjectId(logRecord.getEntityObject()));
          session.save(logRecord);
        }
 else {
          session.evict(logRecord);
        }
      }
 else {
        session.save(logRecord);
      }
    }
  }
 catch (  final HibernateException e) {
    throw new CallbackException(e);
  }
 finally {
    session.flush();
    session.close();
  }
}
 

Example 20

From project Clotho-Core, under directory /ClothoApps/HibernateConnectionLibrary/src/org/clothocad/hibernate/.

Source file: HibernateConnection.java

  19 
vote

public boolean saveDatum(Object toSave){
  Session s=null;
  Transaction t=null;
  try {
    s=fac.openSession();
    t=s.beginTransaction();
    if (toSave != null) {
      s.saveOrUpdate(toSave);
    }
 else {
      return false;
    }
    t.commit();
    s.close();
    return true;
  }
 catch (  RuntimeException e) {
    e.printStackTrace();
    System.err.println("Commit failed!");
    if (t != null && t.isActive()) {
      try {
        t.rollback();
      }
 catch (      HibernateException e1) {
        System.err.println("Rollback failed");
      }
    }
  }
  return false;
}
 

Example 21

From project CloudReports, under directory /src/main/java/cloudreports/dao/.

Source file: CustomerRegistryDAO.java

  19 
vote

/** 
 * Inserts a new customer registry into the database. The customer's name must be unique.
 * @param cr      the customer registry to be inserted.
 * @return          <code>true</code> if the customer registryhas been successfully inserted;  <code>false</code> otherwise.
 * @see CustomerRegistry
 * @since           1.0
 */
public boolean insertNewCustomerRegistry(CustomerRegistry cr){
  Session session=HibernateUtil.getSession();
  try {
    CustomerRegistry customer=(CustomerRegistry)session.createCriteria(CustomerRegistry.class).add(Restrictions.eq("name",cr.getName())).uniqueResult();
    if (customer != null)     return false;
    session.beginTransaction();
    session.save(cr);
    session.getTransaction().commit();
  }
 catch (  HibernateException ex) {
    session.getTransaction().rollback();
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
 finally {
    HibernateUtil.closeSession(session);
  }
  NetworkMapEntryDAO neDAO=new NetworkMapEntryDAO();
  neDAO.insertNewEntityEntries(cr.getName());
  return true;
}
 

Example 22

From project ehour, under directory /eHour-persistence/src/main/java/net/rrm/ehour/persistence/timesheet/dao/.

Source file: TimesheetDaoHibernateImpl.java

  19 
vote

@SuppressWarnings({"unchecked","rawtypes"}) public TimesheetEntry getLatestTimesheetEntryForAssignment(final Integer assignmentId){
  return (TimesheetEntry)getHibernateTemplate().executeWithNativeSession(new HibernateCallback(){
    public Object doInHibernate(    Session session) throws HibernateException {
      List<TimesheetEntry> results;
      Query queryObject=session.getNamedQuery("Timesheet.getLatestEntryForAssignmentId");
      queryObject.setInteger("assignmentId",assignmentId);
      queryObject.setMaxResults(1);
      results=(List<TimesheetEntry>)queryObject.list();
      return ((results != null && results.size() > 0) ? results.get(0) : null);
    }
  }
);
}
 

Example 23

From project faces, under directory /Proyectos/cinedayz/src/main/java/pe/joedayz/ejemplos/cinedayz/core/.

Source file: GenericoDAO.java

  19 
vote

@SuppressWarnings("unchecked") public List<Entidad> obtenerLista(final Busqueda filtro){
  return (List<Entidad>)this.getHibernateTemplate().execute(new HibernateCallback(){
    @Override public Object doInHibernate(    Session session) throws HibernateException, SQLException {
      Criteria busqueda=filtro.getExecutableCriteria(session);
      busqueda.setFirstResult(((Busqueda)filtro).getFirstResult());
      if (filtro.getMaxResults() > 0)       busqueda.setMaxResults(((Busqueda)filtro).getMaxResults());
      return (List<Entidad>)busqueda.list();
    }
  }
);
}
 

Example 24

From project GoFleetLSServer, under directory /src/main/java/org/gofleet/openLS/ddbb/dao/.

Source file: RoutingDAO.java

  19 
vote

@Transactional(readOnly=true) public DetermineRouteResponseType routePlan(final DetermineRouteRequestType param){
  HibernateCallback<DetermineRouteResponseType> action=new HibernateCallback<DetermineRouteResponseType>(){
    @SuppressWarnings("unchecked") public DetermineRouteResponseType doInHibernate(    Session session) throws HibernateException, SQLException {
      Query consulta=session.getNamedQuery("tsp");
      WayPointListType wayPointList=param.getRoutePlan().getWayPointList();
      List<Geometry> stops=new LinkedList<Geometry>();
      for (      WayPointType wayPoint : wayPointList.getViaPoint()) {
        stops.add(GeoUtil.getPoint(wayPoint,null));
      }
      stops.add(GeoUtil.getPoint(wayPointList.getEndPoint(),null));
      consulta.setString("tablename",configuration.get("ROUTING_TABLE","routing"));
      consulta.setParameterList("stoptable",stops,GeometryUserType.TYPE);
      consulta.setString("gid",configuration.get("ROUTING_ID","gid"));
      consulta.setParameter("start",GeoUtil.getPoint(wayPointList.getStartPoint(),null),GeometryUserType.TYPE);
      consulta.setReadOnly(true);
      LOG.debug(consulta);
      return getRouteResponse(consulta.list());
    }
  }
;
  return hibernateTemplate.executeWithNativeSession(action);
}
 

Example 25

From project gxa, under directory /atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/hibernate/.

Source file: SchemaValidatingAnnotationSessionFactoryBean.java

  19 
vote

public void validateDatabaseSchema() throws DataAccessException {
  logger.info("Validating database schema for Hibernate SessionFactory");
  HibernateTemplate hibernateTemplate=new HibernateTemplate(getSessionFactory());
  hibernateTemplate.execute(new HibernateCallback<Object>(){
    public Object doInHibernate(    Session session) throws HibernateException, SQLException {
      Connection con=session.connection();
      Dialect dialect=Dialect.getDialect(getConfiguration().getProperties());
      DatabaseMetadata metadata=new DatabaseMetadata(con,dialect);
      Configuration configuration=getConfiguration();
      configuration.validateSchema(dialect,metadata);
      return null;
    }
  }
);
}