Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

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
      Code Block
      xml
      xml
      <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:
      Code Block
      java
      java
      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
      Code Block
      java
      java
      private DataSource dataSource;
      
    2. Get access to the service using the cover
      Code Block
      java
      java
      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
    Code Block
    java
    java
    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.