ActiveJDBC – as ORM : Concept
- ActiveJdbc Concepts
- Why ORM?
- ActiveJdbc Publication
- Design principles
- Understanding JavaBeans
- Jar File Required
- Performance & Code Compare between ActiveJDBC and Hibernate
- Create/Modify/Delete/List records Using ActiveJDBC
ActiveJdbc Concepts |
Introduction
- ActiveJDBC is developed by Igor Polevoy.
- It is a Java implementation of the ActiveRecord Design Pattern.
- It was inspired by ActiveRecord ORM from Ruby on Rails.
- It is based on a set of conventions and does not require configuration.
- ActiveJDBC is a Java ORM.
- It is fast, lightweight and small and does not require any configuration..
Why ORM? |
When we develop persistence logic for our application with JDBC technology, we need to do the following steps
- Take the Connection
- Create the Statement
- Prepare the SQL Query
- Submit the query to DB engine
- Process the results
- Cleanup the resource
- Handling Exceptions
Which leads
- Creating Problem in Code Duplication.
- Creating Problem in Performance if not tuned properly.
Java Connecting Database through JDBC Style
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("could not load MySQL Driver")
}
try
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/javaskoolDB","root","admin");
Statement st=con.createStatement();
String query="Select * from user where uid=\'"+user.getUserId()+"\'";
ResultSet rs=st.executeQuery(query);
.....
Type of ORM tools Available
- JDBC
- EJB2 [Entity Bean]
- EJB3 [JPA] *
- Hibernate*
- IBaties*
- TopLink*
- JDO*
- ActiveJDBC*
Note :- (*) Means ORM Tool and Hibernate is more popular and best among all other ORM tools
ActiveJdbc Publication |
ActiveJDBC Publication
July 19 2010: ActiveJDBC sources are published on Google Code under Apache 2.0 License.
http://code.google.com/p/activejdbc/
http://www.apache.org/licenses/LICENSE-2.0
Design principles |
Design principles
- Should infer metadata from DB (like ActiveRecord)
- Should be very easy to work with
- Should reduce amount of code to a minimum
- No configuration, just conventions
- Some conventions are overridable in code
- No need to learn another language
- No need to learn another QL – SQL is sufficient
- Code must be lightweight and intuitive, should read like English
- No sessions, no “attaching, re-attaching”
- No persistence managers.
- No classes outside your own models.
- Models are lightweight, no transient fields
- Should have the least possible resistance to startup a project
- No useless getters and setters (they just pollute code). You can still write them if you like.
- No DAOs and DTOs – this is mostly junk code anyway
What ActiveJDBC is not?
- ActiveJDBC is not a layer on top of Hibernate
- ActiveJDBC is not a JPA implementation, it has it’s own annotations and all are optional; the only standard it adheres to is JDBC
Supported databases
Currently ActiveJDBC supports
- MySQL,
- PostgreSQL,
- Oracle,
- H2 and
- MS SQLServer
Understanding JavaBeans |
Understanding JavaBeans
- Java development is all about getters and setters.
- Ever since the Java Beans framework introduced in 1997, this has become a blessing in modern Java applications.
- ActiveJDBC does not require getters and setters for models.
- Since models already know all the allowable metadata from database at startup, they will perform validations of names of attributes.
Writing a Model
Simple models are written in one line of code. No need for setters or getters.
public class Travel extends Model {}
Built in getters and setters
ActiveJDBC provides two base methods for getting information from DB and putting it in
Travel t = Travel.findById();
String pname = t.get("passengerName");
The name is a name of a column from a table travel.
Same goes for a setter:
Travel t = new Travel ();
t.set("passengerName", "James");
p.save();
No “standard” getters/setters?
- Well, no.
- ActiveJDBC will not provide these, and it will not generate them either.
- However, you can have them if you like
public class Person extends Model{
public void setFirstName(String firstName){
set("first_name", firstName);
}
}
Jar File Required |
Jar File Required
- activejdbc-1.4.6.jar
- javalite-common-1.4.6.jar
- mysql-connector-java-5.0.4.jar
- slf4j-api-1.6.4.jar
- slf4j-simple-1.6.4.jar
- Build Time Jar Files
- activejdbc-instrumentation-1.4.6.jar
- javassist-3.16.1-GA.jar
Performance & Code Compare between ActiveJDBC and Hibernate |
Core 2 Duo CPU P8700 @ 2.53GHz, with 8G RAM, 256G SSD and Ubuntu running natively.
- Hibernate insert: 16057 milliseconds
- ActiveJDBC insert: 9630 milliseconds
- Hibernate select: 50000 records in: 1874 milliseconds
- ActiveJDBC select: 50000 records in: 836 milliseconds
Code Compare between ActiveJDBC and Hibernate
Entity class in Hibernate
@Table(name = "employees")
public class Employee implements Serializable {
public Employee() {}
@Id
@Column(name = "id")
@GeneratedValue
Integer id;
@Column(name = "first_name")
String firstName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String toString() {
return "Employee{" +
"class="n + id +
", first_name='" + firstName + '\'' +
'}';
}
}
Model class in ActiveJDBC
public class Employee extends Model{}
Usage of entity in Hibernate
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
List employees = session.createQuery("select e from Employee as e").list();
session.close();
Usage of entity in ActiveJDBC
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test_db", "user1", "****");
List employees = Employee.findAll();
Base.close();
Create/Modify/Delete/List records Using ActiveJDBC |
Create Record
There are many ways to create new records with ActiveJDBC
1. save() and saveIt() methods
ActiveJDBC class Model provides two methods for saving an entity: save() and saveIt().
Both methods will involve validations during saving, but in the case of the method save() will silently exit without throwing exceptions. In case validations failed, the instance will have an errors collection attached to it.
This is very useful in the context of a web application.
Travel t = new Travel ();
t.set("passengerName", "James"");
t.save();
2. Batching names an values
There is a way to batch names and values into arrays:
String[] names = {"first_name", "last_name"};
Object[] values = {"John", "bond"}
new Travel().set(names, values).saveIt();
3. Convenience create() and createIt() methods
The class Model also provides two convenience methods for creation of records: create() and createIt(). There is a semantic
difference between these two methods, and it is the same as between save() and saveIt() methods, except in this case,
ActiveJDBC creates and attempts to save an object in one step.
Travel t = Travel .create("first_name", "Sam", "last_name", "peter");
t.saveIt();
Travel t = Travel .createIt("first_name", "Sam", "last_name", " peter ");
t.saveIt();
The create() and createIt() method accepts a list of arguments, where names are interleaved with values.
Modify Record
This snippet should also be self-explanatory:
Travel t = Travel.findFirst("first_name = ?", "james");
t.set("last_name", "bond");
t.saveIt();
Delete Record
Deleting a record
Travel t = Travel.findFirst("first_name = ?", "james");
t.delete();
Deleting all records
Travel.deleteAll();
List Record
Selecting all records
List<Travel> tlist = Travel .findAll();
Finding a single record
Travel t = Travel .findFirst("first_name = ?", "james");
This line will find an instance of Employee (conditionally), if one exists, or null if one does not exist.
Finding some records
List<Travel> tlist= Travel .where("first_name = ?", "james");
Recent Comments