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
- Using Spring to get the service for your class (e.g. YourAppClass) (recommended)
- 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>
- 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; }
- Add the DataSource bean to the bean for YourAppClass
- Using the cover to get the service
- Note: This is not the recommended method, you should be using Spring to inject the service
- Setup a variable to hold the instance from the cover
private DataSource dataSource;
- Get access to the service using the cover
dataSource = (DataSource) ComponentManager.get(DataSource.class);
Getting the connection from the datasource
- 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.