Although ActiveJDBC has advanced features, simple things are very easy. This page shows simplest cases of DB access with ActiveJDBC.
- Java :)
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.
See example project: Simple Maven - based example.
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) );
Add ActiveJDBC dependency
Change version to latest.
Add ActiveJDBC Instrumentation plugin
Add the following to the plugins section of the POM:
Write a model
This is the easiest thing - writing a simple model is usually done with one line of code:
Please, note that the name of a table is
employees - plural, and the name of a model is
Employee - singular. If you are wondering how this is done, you can take a look at the Inflector class. ActiveJDBC uses inflections of English language to do conversion of plural and singular forms of words. This of course can be overridden by a
Open a connection
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
This is self-explanatory. Models are somewhat like maps. There are no setters or getters. You can still write them if you like, see Setters and getters for more information.
The same logic can be written in one line:
The framework has quite a few shortcuts like this one.
Finding a single record
This line will find an instance of Employee (conditionally), if one exists, or null if one does not exist.
Finding some records
Updating a record
This snippet should also be self-explanatory:
Deleting a record
Deleting all records
Selecting all records
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://github.com/javalite/ant-example Please see README file there.
This introduction provides enough information to get started. It also shows how simple ActiveJDBC APIs are. This ORM has many advanced features, such as automatic recognition of associations, caching, validations, polymorphic associations, etc. The code used on this page can be found in this simple project: https://github.com/javalite/simple-example.
How to comment
The comment section below is to discuss documentation on this page.
If you have an issue, or discover bug, please follow instructions on the Support page