Java Code Examples for org.hibernate.Session

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 accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: NotificationUtil.java

  23 
vote

public static Notification saveNotification(Notification notification) throws ServiceException {
  Session hibernate=HibernateUtil.getSession();
  hibernate.beginTransaction();
  try {
    hibernate.saveOrUpdate(notification);
    hibernate.getTransaction().commit();
    return notification;
  }
 catch (  Throwable ex) {
    logger.error("No se ha podido almacenar la notificaci?n",ex);
    hibernate.getTransaction().rollback();
    throw new ServiceException();
  }
}
 

Example 2

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

Source file: RequestServiceImpl.java

  22 
vote

@Override public void deleteRequest(Request request) throws ServiceException {
  Session hibernate=HibernateUtil.getSession();
  hibernate.beginTransaction();
  try {
    hibernate.delete(request);
    hibernate.getTransaction().commit();
  }
 catch (  Throwable ex) {
    hibernate.getTransaction().rollback();
    throw new ServiceException();
  }
}
 

Example 3

From project agile, under directory /agile-apps/agile-app-admin/src/main/java/org/headsupdev/agile/app/admin/.

Source file: Membership.java

  22 
vote

protected void onSubmit(){
  Session session=HibernateUtil.getCurrentSession();
  Set<User> defaultProjectMembers=new HashSet<User>();
  for (  User user : users) {
    user=(User)session.merge(user);
    user.getProjects().clear();
    for (    Project project : projects) {
      submitProject(project,user,defaultProjectMembers);
    }
  }
  StoredProject.setDefaultProjectMembers(defaultProjectMembers);
  StoredProject.getDefault().getUsers().clear();
  StoredProject.getDefault().getUsers().addAll(defaultProjectMembers);
}
 

Example 4

From project agile, under directory /agile-apps/agile-app-admin/src/main/java/org/headsupdev/agile/app/admin/.

Source file: Permissions.java

  22 
vote

protected void onSubmit(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction tx=session.beginTransaction();
  for (  User user : users) {
    user=(User)session.merge(user);
    if (user.getUsername().equals(((HeadsUpSession)getSession()).getUser().getUsername())) {
      ((HeadsUpSession)getSession()).setUser(user);
    }
  }
  tx.commit();
}
 

Example 5

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

Source file: HibernateUtil.java

  22 
vote

public static Session currentSession() throws HibernateException {
  Session s=(Session)session.get();
  if (s == null) {
    s=sessionFactory.openSession();
    session.set(s);
  }
  return s;
}
 

Example 6

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

Source file: HibernateUtil.java

  22 
vote

public static void startHibernateTransaction() throws HibernateException {
  Session hibSession=currentSession();
  try {
    hibSession.beginTransaction();
  }
 catch (  HibernateException hex) {
    closeSession();
    throw hex;
  }
}
 

Example 7

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

Source file: HibernateBookmarkStore.java

  22 
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 8

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

Source file: HibernateBookmarkStore.java

  22 
vote

/** 
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#storeBookmarkSet(edu.wisc.my.portlets.bookmarks.domain.BookmarkSet)
 */
public void storeBookmarkSet(BookmarkSet bookmarkSet){
  try {
    final Session session=this.getSession(false);
    if (bookmarkSet.getId() == -1) {
      this.removeBookmarkSet(bookmarkSet.getOwner(),bookmarkSet.getName());
      session.save(bookmarkSet);
    }
    session.update(bookmarkSet);
    session.flush();
  }
 catch (  HibernateException ex) {
    throw convertHibernateAccessException(ex);
  }
}
 

Example 9

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

Source file: UserService.java

  22 
vote

@Transactional public User query(String login,String password){
  User result=null;
  Session session=sf.getCurrentSession();
  Query query=session.getNamedQuery("user.login");
  query.setParameter("login",login);
  result=(User)query.uniqueResult();
  if (result != null) {
    if (!encoder.check(password.trim(),result.getPasswordHash())) {
      result=null;
    }
  }
  return result;
}
 

Example 10

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

Source file: AbstractHibernateCurator.java

  22 
vote

public void saveOrUpdateAll(List<E> entries){
  Session session=currentSession();
  for (int i=0; i < entries.size(); i++) {
    session.saveOrUpdate(entries.get(i));
    if (i % batchSize == 0) {
      session.flush();
      session.clear();
    }
  }
}
 

Example 11

From project capedwarf-green, under directory /server-jee/src/main/java/org/jboss/capedwarf/server/jee/persistence/.

Source file: HibernateStatelessAdapterFactory.java

  22 
vote

protected StatelessAdapter doCreateStatelessAdapter(EntityManager em){
  Object delegate=em.getDelegate();
  if (delegate instanceof Session == false)   throw new IllegalArgumentException("Can only handle Hibernate Session: " + delegate);
  Session session=(Session)delegate;
  SessionFactory factory=session.getSessionFactory();
  return new HibernateStatelessAdapter(factory.openStatelessSession());
}
 

Example 12

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

Source file: HibernateConnection.java

  22 
vote

@Override public ObjBaseDatum getDatum(ObjType type,String uuid){
  Session s=fac.openSession();
  hibernateDatum data=getHibernateDatum(type,uuid,s);
  ObjBaseDatum out=null;
  if (data != null) {
    out=data.getObjBaseDatum();
  }
 else {
    out=null;
  }
  s.close();
  return out;
}
 

Example 13

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

Source file: HibernateConnection.java

  22 
vote

/** 
 * Retrieves an ObjBase object from the database using a uuid
 * @param type
 * @param uuid
 * @return
 */
@Override public ObjBase get(ObjType type,String uuid){
  Session s=fac.openSession();
  hibernateDatum d=getHibernateDatum(type,uuid,s);
  ObjBase result=null;
  if (d != null) {
    result=d.getObject();
    SearchtagTable.pullSearchTags(result);
  }
  s.close();
  return result;
}
 

Example 14

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

Source file: CustomerRegistryDAO.java

  22 
vote

/** 
 * Gets an existing customer with the given name.
 * @param customerName    the name of the customer to be retrieved.
 * @return                  the customer, if it exists; <code>null</code>otherwise.
 * @see CustomerRegistry
 * @since                   1.0
 */
public CustomerRegistry getCustomerRegistry(String customerName){
  Session session=HibernateUtil.getSession();
  CustomerRegistry customer=null;
  try {
    customer=(CustomerRegistry)session.createCriteria(CustomerRegistry.class).add(Restrictions.eq("name",customerName)).uniqueResult();
  }
 catch (  HibernateException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
 finally {
    HibernateUtil.closeSession(session);
  }
  return customer;
}
 

Example 15

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

Source file: CustomerRegistryDAO.java

  22 
vote

/** 
 * Gets an existing customer with the given id.
 * @param customerId      the id of the customer to be retrieved.
 * @return                  the customer, if it exists; <code>null</code>otherwise.
 * @see CustomerRegistry
 * @since                   1.0
 */
public CustomerRegistry getCustomerRegistry(long customerId){
  Session session=HibernateUtil.getSession();
  CustomerRegistry customer=null;
  try {
    customer=(CustomerRegistry)session.createCriteria(CustomerRegistry.class).add(Restrictions.eq("id",customerId)).uniqueResult();
  }
 catch (  HibernateException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
 finally {
    HibernateUtil.closeSession(session);
  }
  return customer;
}
 

Example 16

From project azure4j-blog-samples, under directory /SQLAzure/SqlAzureHibernate/src/com/persistent/azure/.

Source file: HibernateAccess.java

  21 
vote

/** 
 * main method
 * @param args
 */
public static void main(String[] args){
  SessionFactory sessionFactory=buildSessionFactory();
  Session session;
  session=sessionFactory.openSession();
  session.beginTransaction();
  try {
    @SuppressWarnings("unchecked") List<Employee> employeeList=session.createQuery("from Employee").list();
    Employee employee=null;
    for (int index=0; index < employeeList.size(); index++) {
      employee=employeeList.get(index);
      System.out.println(employee.getName());
    }
  }
 catch (  Exception e) {
  }
 finally {
    session.close();
  }
}
 

Example 17

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

Source file: Bootstrapper.java

  21 
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 18

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

Source file: AuditTrailInterceptor.java

  21 
vote

@SuppressWarnings("unchecked") @Override public boolean onFlushDirty(final Object entity,final Serializable id,final Object[] currentState,final Object[] previousState,final String[] propertyNames,final Type[] types) throws CallbackException {
  boolean returnCode=false;
  if (entity instanceof TimelineVersionable) {
    returnCode=true;
    final Date date=new Date();
    final Integer userId=getCurrentUserId();
    setValue(currentState,propertyNames,"lastChangedBy",userId);
    setValue(currentState,propertyNames,"lastChangeDate",date);
  }
  if (entity.getClass().isAnnotationPresent(Audit.class)) {
    returnCode=true;
    final Session session=sessionFactory.openSession();
    final Class objectClass=entity.getClass();
    final String className=objectClass.getSimpleName();
    final Serializable persistedObjectId=getObjectId(entity);
    final Object preUpdateState=session.get(objectClass,persistedObjectId);
    try {
      logChanges(entity,preUpdateState,persistedObjectId,AuditRecord.UPDATE,className);
    }
 catch (    final Exception e) {
      e.printStackTrace();
    }
    session.close();
  }
  return returnCode;
}
 

Example 19

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

Source file: AuditTrailInterceptor.java

  21 
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 arquillian-showcase, under directory /spring/spring-hibernate/src/test/java/com/acme/spring/hibernate/.

Source file: HibernateTestHelper.java

  19 
vote

/** 
 * <p>Executes a sql script.</p>
 * @param session the hibernate session
 * @param fileName     the file name
 * @throws java.io.IOException if any error occurs
 */
public static void runScript(Session session,String fileName) throws IOException {
  InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
  BufferedReader inputReader=new BufferedReader(new InputStreamReader(input));
  StringBuilder stringBuilder=new StringBuilder();
  String line;
  while ((line=inputReader.readLine()) != null) {
    if (!line.startsWith("--")) {
      stringBuilder.append(line);
    }
  }
  String[] commands=stringBuilder.toString().split(";");
  for (  final String command : commands) {
    session.doWork(new Work(){
      public void execute(      Connection connection) throws SQLException {
        connection.prepareStatement(command).execute();
      }
    }
);
  }
}
 

Example 21

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 22

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

Source file: UserDAOImpl.java

  19 
vote

public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
  return (UserDetails)getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(    Session session) throws HibernateException, SQLException {
      return session.createCriteria(Member.class).add(Restrictions.eq("username",username)).uniqueResult();
    }
  }
);
}