Table of contents
  1. Grails Notes
    1. Access to session and hibernate
      1. getting session
    2. get hibernate datastore in session
      1. Get hibernatedatasource
      2. get table columns
      3. get data bindings/properties/class/domain table/declared fields
      4. Get A Service




Grails Notes

Access to session and hibernate

  • getting session

      def sessionFactory
    
      def session = sessionFactory?.getCurrentSession()
    
      RequestContextHolder.currentRequestAttributes().getSession()
    
  • get hibernate datastore in session

    • Get hibernatedatasource

      hibernate datastore ex.

         public class HibernateExample {
               @Autowired
               HibernateDatastore hibernateDatastore;
                 
               @Autowired
               DatabaseProvisioningService databaseProvisioningService;
                 
               @Listener(User)
               void onUserPostInsertEvent(PostInsertEvent event) {
                   String username = event.getEntityAccess().getPropertyValue("username");
                   DatabaseConfiguration databaseConfiguration = databaseProvisioningService.findDatabaseConfigurationByUsername(username);
                   hibernateDatastore.getConnectionSources().addConnectionSource(databaseConfiguration.dataSourceName, databaseConfiguration.configuration);
               }
           }
      
    • get table columns

      hibernateDatastore.getSessionFactory().getClassMetadata(GroupCompare).getProperties().sort()
      
      ctx.sessionFactory.getClassMetadata(Team).attributes.collect { it.name }
      
    • get data bindings/properties/class/domain table/declared fields

      def mapping = org.grails.orm.hibernate.cfg.GrailsDomainBinder.getMapping(UserGroup)
      
      def mapping = org.grails.orm.hibernate.cfg.GrailsDomainBinder.getMapping(UserGroup)
      
      org.grails.orm.hibernate.cfg.GrailsDomainBinder.getMapping(groupCompare.class).class.declaedFields
      
    • Get A Service

    1.  public class HibernateExample {
           
            @Autowired
            HibernateDatastore hibernateDatastore;
            UserDataService userDataService;
           
            UserService(HibernateDatastore hibernateDatastore) {
                this.userDataService = hibernateDatastore.getService(UserDataService);
            }
         }
      
    2.   (YourService)Holders.grailsApplication.mainContext["yourService"];
      
    3.   applicationContext."${yourServiceName}".serviceMethod();
      
    4.   ctx.getBean("userGroupService");
      
    5.   Holders.applicationContext.getBean("myService");
      
   class HibernateExample {

    ApplicationContext ctx = (ApplicationContext) ServletContextHolder
            .getServletContext()
            .getAttribute(GrailsApplicationAttributes
                    .APPLICATION_CONTEXT)

    def statisticsService = (StatisticsService).ctx.getBean("statisticsService ")
}