My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
GettingStarted  
this page explains how to get started with ActiveJDBC
Updated Jan 10, 2012 by ipole...@gmail.com

Although ActiveJDBC has advanced features, simple things are very easy. This page shows simplest cases of DB access with ActiveJDBC.

Pre-requisite

  • Java (obvious)
  • Maven
  • To see what makes ActiveJDBC tick, you can pull sources: svn checkout http://activejdbc.googlecode.com/svn/trunk/ activejdbc-read-only

Create a standard Maven project structure

While ActiveJDBC does not have to be used with Maven, this example (as well as ActiveJDBC itself) was built with Maven. To see the project itself, you can check it out from SVN:

svn co https://activejdbc.googlecode.com/svn/trunk/examples/simple-example/

The best way is to check out this project and start playing with it. Take a look at the run.sh script at the root of this example project.

Create a table

This is an SQL statement to create a table (MySQL used for this example):

CREATE TABLE employees (
      id  int(11) DEFAULT NULL auto_increment PRIMARY KEY,
      first_name VARCHAR(56),
      last_name VARCHAR(56)
  );

Maven configuration

Add ActiveJDBC dependency

            <dependency>
                <groupId>org.javalite</groupId>
                <artifactId>activejdbc</artifactId>
                <version>1.2-SNAPSHOT</version>
            </dependency>

Add ActiveJDBC Instrumentation plugin

In the plugins section of the POM, add this:

            <plugin>
                <groupId>org.javalite</groupId>
                <artifactId>activejdbc-instrumentation</artifactId>
                <version>1.2-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>instrument</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Add repositories for ActiveJDBC snapshots

    <repositories>
        <repository>
            <id>sonatype-snapshots</id>
            <name>Sonatype Snapshot Repo</name>
            <layout>default</layout>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
                <checksumPolicy>warn</checksumPolicy>
                <updatePolicy>always</updatePolicy>
            </snapshots>

        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>sonatype-plugin-snapshots</id>
            <name>Sonatype Snapshot Repo</name>
            <layout>default</layout>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
                <checksumPolicy>warn</checksumPolicy>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    

Write a model

This is the easiest thing - writing a simple model is usually done with one line of code:

import activejdbc.Model;

public class Employee extends Model {}

Please, note that the name of a table is "employees" - plural, and the name of a model is "Employee" - singular. ActiveJDBC uses inflections of English language to do conversion of plural and singular forms of words. This of course can be overridden by @Table annotation.

Open a connection

Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test", "root", "p@ssw0rd");

Replace the values for the ones that make sense for your environment. Base is a utility class that allows to perform some basic (hence the name) JDBC operations, one of them is opening a connection. The connection object is then attached to the current thread, and can be consumed by any ActiveJDBC API.

Create a new record

Employee e = new Employee();
e.set("first_name", "John");
e.set("last_name", "Doe");
e.saveIt();

I hope this is self-explanatory. ActiveJDBC models somewhat behave like maps. There are no setters or getters. You can still write them if you like.

Finding a single record

Employee e = Employee.findFirst("first_name = ?", "John");

This line will find an instance of Employee (conditionally), if one exists, or null if one does not exist.

Finding some records

List<Employee> employees = Employee.where("first_name = ?", "John");

Updating a record

This snippet should also be self-explanatory:

Employee e = Employee.findFirst("first_name = ?", "John");
e.set("last_name", "Steinbeck").saveIt();

Deleting a record

Employee e = Employee.findFirst("first_name = ?", "John");
e.delete();

Deleting all records

Employee.deleteAll();

Selecting all records

List<Employee> employees = Employee.findAll();

Sample project using Ant

If you are not using Maven, you can use Ant. Example of exactly the same project with all necessary dependencies can be found here: https://activejdbc.googlecode.com/svn/trunk/examples/ant-example/ Please see README file there.

Conclusion

I hope this quick introduction provides enough information to get started. It also shows how simple ActiveJDBC APIs are. The project has many advanced features, such as automatic recognition of associations, caching, validations, polymorphic associations, etc. The examples on this page can be found and executed in the included Maven project here: https://activejdbc.googlecode.com/svn/trunk/examples/simple-example/

Read the Features section for a more in depth information on the framework.

Enjoy

Comment by mauricio.porras.p, Feb 20, 2011

Welcome to the future! : )

Comment by arafat...@gmail.com, Feb 28, 2011

Hello !

Why we cannot us AJ without maven ? and how can we do to us it without maven ? witch are the lib that must be found in the project classpath to run this example ?

king regards

Comment by project member ipole...@gmail.com, Feb 28, 2011

Arafat, I added "Sample project using Ant" section to this page, this should answer your question

cheers

Comment by elhosin....@gmail.com, Jun 6, 2011

Excellent work :) please keep it up.

Comment by javadba@gmail.com, Jun 19, 2011

Lacking the getters/setters is a major detraction to this framework. Is there any plan to add that?

Comment by javadba@gmail.com, Jun 19, 2011

Any documentation / notes on the connection management? i.e. if we call Base.open() ten times on the same thread is the ThreadLocal? handling it properly and actually only getting one connection and then returning the same connection again the other nine times? Also is the Connection pooled (to avoid disastrous performance as well as resource exhaustion) ?

thanks

Comment by javadba@gmail.com, Jun 19, 2011

I have found that the existing threadLocal connection management does not suit following web server scenarios:

(a) the number of web server threads exceeds the allowable concurrent db connections (b) the web server continually generates new threads (causing us to continually experience the delay of establishing new connections )

Are you open to a patch that I have implemented that provides a ConnectionPooling? mechanism? The new classes include

-- PooledConnectionJdbcSpec?, PooledConnectionAccess? -- additional "maxConnections" parameter -- The semantics are a bit different: the client explicitly obtains/releases connection from/to the pool.

This pooledConnection is not for use in all scenarios but is required for our high concurrency stateless short-lived requests scenario .

Please post here about the possibility of working in this contrib.

stephenb I have implemented

Comment by project member ipole...@gmail.com, Jun 19, 2011

javadba: lacking setters and getters is by design. I do not see this as a hindrance, but rather as an advantage. For more in this, you can refer to this page: SettersAndGetters. There are plenty of other frameworks that require getters and setters, but with ActibveJDBC you have a choice.

Comment by project member ipole...@gmail.com, Jun 19, 2011

javadba: I added this: DatabaseConnectionManagement for better understanding of connection management within ActiveJDBC

Comment by project member ipole...@gmail.com, Jun 19, 2011

javadba: I certainly welcome contributions, and you can see in code that many people contributed to this framework. However, I do not believe that pool integration or pool management belongs in this framework. Java containers already do an excellent job doing this.

As far as scenarios when a connection pool can become depleted, this is possible, but not specific to ActiveJDBC and can happen to any environment. The other framework I wrote, ActiveWeb allows to configure connections for specific controllers and even actions so that you could avoid opening connections for HTTP requests that do not require one: http://code.google.com/p/activeweb/wiki/ControllerFilters#DBConnectionFilter

cheers,

igor

Comment by canc...@gmail.com, Aug 5, 2011

Support MSSQL2000? or MSSQL2005???

Comment by project member ipole...@gmail.com, Aug 5, 2011

Support for MS SQL is not available yet.

Comment by tiefenth...@gmail.com, Sep 16, 2011

Hi!

I can't get this working. What I did so far: I checked out using the svn command above and added the plugin and the dependency to the pom.xml. Then I ran the script and got this output:

./run.sh BUILDING MODULE INFO? Scanning for projects... WARNING? WARNING? Some problems were encountered while building the effective model for org.javalite:activeJdbc-simple-example:jar:1.2-SNAPSHOT WARNING? 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 24, column 21 WARNING? WARNING? It is highly recommended to fix these problems because they threaten the stability of your build. WARNING? WARNING? For this reason, future Maven versions might no longer support building such malformed projects. WARNING? INFO? INFO? ------------------------------------------------------------------------ INFO? Building activeJdbc-simple-example 1.2-SNAPSHOT INFO? ------------------------------------------------------------------------ Downloading: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml Downloaded: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml (372 B at 0.3 KB/sec) Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available INFO? ------------------------------------------------------------------------ INFO? BUILD FAILURE INFO? ------------------------------------------------------------------------ INFO? Total time: 2.240s INFO? Finished at: Fri Sep 16 09:19:37 CEST 2011 INFO? Final Memory: 2M/81M INFO? ------------------------------------------------------------------------ ERROR? Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT: Could not find artifact org.javalite:activejdbc-instrumentation:pom:1.2-SNAPSHOT in ipsolutionsdev-plugin-snapshots (http://ipsolutionsdev.com/snapshots/) -> 1? ERROR? ERROR? To see the full stack trace of the errors, re-run Maven with the -e switch. ERROR? Re-run Maven using the -X switch to enable full debug logging. ERROR? ERROR? For more information about the errors and possible solutions, please read the following articles: ERROR? 1? http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException COLLECTING DEPENDENCIES INFO? Scanning for projects... WARNING? WARNING? Some problems were encountered while building the effective model for org.javalite:activeJdbc-simple-example:jar:1.2-SNAPSHOT WARNING? 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 24, column 21 WARNING? WARNING? It is highly recommended to fix these problems because they threaten the stability of your build. WARNING? WARNING? For this reason, future Maven versions might no longer support building such malformed projects. WARNING? Downloading: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml Downloaded: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml (372 B at 0.7 KB/sec) Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available WARNING? Failed to retrieve plugin descriptor for org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT: Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT INFO? INFO? ------------------------------------------------------------------------ INFO? Building activeJdbc-simple-example 1.2-SNAPSHOT INFO? ------------------------------------------------------------------------ Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available WARNING? Failed to retrieve plugin descriptor for org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT: Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT WARNING? The POM for activejdbc:activejdbc:jar:1.0-SNAPSHOT is missing, no dependency information available INFO? ------------------------------------------------------------------------ INFO? BUILD FAILURE INFO? ------------------------------------------------------------------------ INFO? Total time: 2.310s INFO? Finished at: Fri Sep 16 09:19:41 CEST 2011 INFO? Final Memory: 4M/81M INFO? ------------------------------------------------------------------------ ERROR? Failed to execute goal on project activeJdbc-simple-example: Could not resolve dependencies for project org.javalite:activeJdbc-simple-example:jar:1.2-SNAPSHOT: Could not find artifact activejdbc:activejdbc:jar:1.0-SNAPSHOT -> 1? ERROR? ERROR? To see the full stack trace of the errors, re-run Maven with the -e switch. ERROR? Re-run Maven using the -X switch to enable full debug logging. ERROR? ERROR? For more information about the errors and possible solutions, please read the following articles: ERROR? 1? http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException EXECUTING PROGRAM Exception in thread "main" java.lang.NoClassDefFoundError?: activejdbc/examples/simple/SimpleExample? Caused by: java.lang.ClassNotFoundException?: activejdbc.examples.simple.SimpleExample?

at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController?.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader?.loadClass(ClassLoader?.java:306) at sun.misc.Launcher$AppClassLoader?.loadClass(Launcher.java:301) at java.lang.ClassLoader?.loadClass(ClassLoader?.java:247)

Because the output told me, I added a version to maven-compiler-plugin (2.3.2). After that I got the following output:

./run.sh BUILDING MODULE INFO? Scanning for projects... INFO? INFO? ------------------------------------------------------------------------ INFO? Building activeJdbc-simple-example 1.2-SNAPSHOT INFO? ------------------------------------------------------------------------ Downloading: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml Downloaded: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml (372 B at 0.5 KB/sec) Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available INFO? ------------------------------------------------------------------------ INFO? BUILD FAILURE INFO? ------------------------------------------------------------------------ INFO? Total time: 1.801s INFO? Finished at: Fri Sep 16 09:21:20 CEST 2011 INFO? Final Memory: 2M/81M INFO? ------------------------------------------------------------------------ ERROR? Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT: Could not find artifact org.javalite:activejdbc-instrumentation:pom:1.2-SNAPSHOT in ipsolutionsdev-plugin-snapshots (http://ipsolutionsdev.com/snapshots/) -> 1? ERROR? ERROR? To see the full stack trace of the errors, re-run Maven with the -e switch. ERROR? Re-run Maven using the -X switch to enable full debug logging. ERROR? ERROR? For more information about the errors and possible solutions, please read the following articles: ERROR? 1? http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException COLLECTING DEPENDENCIES INFO? Scanning for projects... Downloading: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml Downloaded: http://ipsolutionsdev.com/snapshots/activejdbc/activejdbc-instrumentation/1.0-SNAPSHOT/maven-metadata.xml (372 B at 0.7 KB/sec) Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/maven-metadata.xml Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available WARNING? Failed to retrieve plugin descriptor for org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT: Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT INFO? INFO? ------------------------------------------------------------------------ INFO? Building activeJdbc-simple-example 1.2-SNAPSHOT INFO? ------------------------------------------------------------------------ Downloading: http://ipsolutionsdev.com/snapshots/org/javalite/activejdbc-instrumentation/1.2-SNAPSHOT/activejdbc-instrumentation-1.2-SNAPSHOT.pom WARNING? The POM for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT is missing, no dependency information available WARNING? Failed to retrieve plugin descriptor for org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT: Plugin org.javalite:activejdbc-instrumentation:1.2-SNAPSHOT or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.javalite:activejdbc-instrumentation:jar:1.2-SNAPSHOT WARNING? The POM for activejdbc:activejdbc:jar:1.0-SNAPSHOT is missing, no dependency information available INFO? ------------------------------------------------------------------------ INFO? BUILD FAILURE INFO? ------------------------------------------------------------------------ INFO? Total time: 2.274s INFO? Finished at: Fri Sep 16 09:21:23 CEST 2011 INFO? Final Memory: 4M/81M INFO? ------------------------------------------------------------------------ ERROR? Failed to execute goal on project activeJdbc-simple-example: Could not resolve dependencies for project org.javalite:activeJdbc-simple-example:jar:1.2-SNAPSHOT: Could not find artifact activejdbc:activejdbc:jar:1.0-SNAPSHOT -> 1? ERROR? ERROR? To see the full stack trace of the errors, re-run Maven with the -e switch. ERROR? Re-run Maven using the -X switch to enable full debug logging. ERROR? ERROR? For more information about the errors and possible solutions, please read the following articles: ERROR? 1? http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException EXECUTING PROGRAM Exception in thread "main" java.lang.NoClassDefFoundError?: activejdbc/examples/simple/SimpleExample? Caused by: java.lang.ClassNotFoundException?: activejdbc.examples.simple.SimpleExample?

at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController?.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader?.loadClass(ClassLoader?.java:306) at sun.misc.Launcher$AppClassLoader?.loadClass(Launcher.java:301) at java.lang.ClassLoader?.loadClass(ClassLoader?.java:247)

Now I don't know what to do. I'm (thanks to this project) new to Maven so ... :-).

Thank you!

Best regards felix

Comment by project member ipole...@gmail.com, Sep 16, 2011

felix, my fault, this example program was broken after a recent refactoring, please get sources and try agan. Going forward, please post problems of this sort to the forum: https://groups.google.com/forum/#!forum/activejdbc-group


Sign in to add a comment
Powered by Google Project Hosting