JDBC in Sakai

Information

This explains basic usage of JDBC in Sakai. JDBC is used whether you are using Hibernate, Spring JDBC, GenericDAO or some other database technology wrapper.
Note: The Sakai Datasource uses a connection pool so you do not have to worry about the cost of opening and closing connections.

Accessing the DataSource

  • You can use Spring Framework to inject the service or use the cover
  1. Using Spring to get the service for your class (e.g. YourAppClass) (recommended)
    1. Add the DataSource bean to the bean for YourAppClass
      <bean id="org.sakaiproject.yourapp.logic.YourAppClass"
      		class="org.sakaiproject.yourapp.logic.impl.YourAppClassImpl">
      	<property name="dataSource"
      		ref="javax.sql.DataSource" />
      </bean>
      
    2. Add a variable and setter to YourAppClass to use the service in like so:
      private DataSource dataSource;
      public void setDataSource(DataSource dataSource) {
      	this.dataSource = dataSource;
      }
      
  2. Using the cover to get the service
    • Note: This is not the recommended method, you should be using Spring to inject the service
    1. Setup a variable to hold the instance from the cover
      private DataSource dataSource;
      
    2. Get access to the service using the cover
      dataSource = (DataSource) ComponentManager.get(DataSource.class);
      

Getting the connection from the datasource

  1. Use the service variable to access the service and get the current User
    Connection conn = dataSource.getConnection();
    try {
        // do things with your connection (select, insert, delete, etc.)
    } finally {
        conn.close();
    }
    
    • Note: Always close your connection in a finally block to ensure that it closes.