Oct 31, 2008

Intro to JQuery

JQuery is a lightweight JavaScript framework that got a lot of attention lately so I decided to write few rows about it.

This post-tutorial is recommended for people with basic javascript, html and css knowledge.

To run and test the examples in this tutorial, you need to save them as html pages. You can use any text editor like notepad or anything convenient.

What do you need to start using JQuery? Just download and save it in the same directory (I’ll call it jquery.js) and include the following code anywhere above your javascript code:


<script type="text/javascript" src="jquery.js"></script>



The best place for our javascript code is in the head section of the html document but you are not restricted to it. Anyway I’ll use the head section for most of my examples.

Ok, let’s use some basic functionality to test if we’ve done it right.

example1.html:

<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert('Works!!!');
} );
</script>
</head>
<body>
JQuery basic tutorial
</body>
</html>




So, what happens here? Nothing special, we just show an alert with text ‘Works!!!’.

$ function is a factory method (shortcut) for the JQuery object.


$(document).ready(function() {
// code
});



With $(document).ready we register our code to the ready event of the document. The above code can be shortened:


$(function () {
// code
} );



Selectors and events



In JQuery an element can be selected in different ways – by id, by element type, by css class and so on.
This is a simple code showing how to use events and selectors:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
alert("Click");
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
Div
</div>
</body>
</html>



The click(fn) binds a function to the click event of our matched element.
Let’s make our example a little more complex. We will count the clicks.


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function () {
$("#ourID").click(function () {
counter++;
$(this).html(counter);
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
0
</div>
</body>
</html>


Oct 28, 2008

Fast and easy Hibernate example-tutorial (Part 2)

Fast and easy Hibernate example-tutorial (Part 1)

In the first part of this tutorial we met the basic functionality of Hibernate. We store and retrieve some simple objects to and from the database.

This time I’ll make the example a little harder. Now our table books will have author_id instead of author(simple string for the name) and we will have table authors with two columns: id, name.

Let’s assume that our book can have single author but our authors may have many books. It is rather dull example, far away from the real world where one book may be written by more than ten people but it would be easy for my example this way.

Also I'll make the id keys serial - I don't want to bother to set ids.

Here is the Author class:

public class Author {
private Integer id;
private String name;

public Integer getId() {
return id;
}

public String getName() {
return name;
}

public void setId(Integer id) {
this.id = id;
}

public void setName(String name) {
this.name = name;
}
}


And the Author.hbm.xml mapping:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Author" table="authors">

<id name="id" type="java.lang.Integer" column="id">
<generator class="sequence">
<param name="sequence">authors_id_seq</param>
</generator>
</id>


<property name="name" column="name" type="java.lang.String" />

</class>
</hibernate-mapping>


Book.java:

public class Book {
private Integer id;
private String title;
private Author author;

public Integer getId() {
return id;
}

public String getTitle() {
return title;
}

public Author getAuthor() {
return author;
}

public void setId(Integer id) {
this.id = id;
}

public void setTitle(String title) {
this.title = title;
}

public void setAuthor(Author author) {
this.author = author;
}
}


Book.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Book" table="books">
<id name="id" type="java.lang.Integer" column="id">

<generator class="sequence">

<param name="sequence">books_id_seq</param>

</generator>
</id>
<property name="title" column="title" type="java.lang.String" />

<many-to-one name="author" class="Author" lazy="false">
<column name="author_id"></column>
</many-to-one>

</class>
</hibernate-mapping>


And finally the hibernate.cfg.xml:

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/example</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">secret</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>

<mapping resource="Author.hbm.xml" />
<mapping resource="Book.hbm.xml" />

</session-factory>
</hibernate-configuration>


We have our classes and now we are ready to test them. This is a simple test example for storing objects:

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookExample {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Author author = new Author();
author.setName("Crazy book author First");
Author author2 = new Author();
author2.setName("Writer");
Book book = new Book();
book.setTitle("Crazy book");
book.setAuthor(author);
Book book2 = new Book();
book2.setTitle("Crazy old book");
book2.setAuthor(author);
Book book3 = new Book();
book3.setTitle("Book Title");
book3.setAuthor(author2);

Transaction tx = session.beginTransaction();
session.save(author);
session.save(author2);
session.save(book);
session.save(book2);
session.save(book3);

tx.commit();

session.close();
sessionFactory.close();
}
}

The result must be something like this:
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)


And now to retrieve the objects from the database:

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookExample2 {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();


Criteria criteria = session.createCriteria(Book.class);
List books = criteria.list();

Iterator it = books.iterator();
while (it.hasNext()) {
Book book = (Book) it.next();
System.out.println("Book: " + book.getTitle() + " with author: " + book.getAuthor().getName());
}

session.close();
sessionFactory.close();
}
}



The result:
Hibernate: select this_.id as id1_0_, this_.title as title1_0_, this_.author_id as author3_1_0_ from books this_
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Book: Crazy book with author: Crazy book author First
Book: Book Title with author: Writer
Book: Crazy old book with author: Crazy book author First


In this example I use few rather interesting options. The first is the generator child element of id with option sequence. It uses a sequence from our database (PostgreSQL, remember? ).
The second is many-to-one relation between the objects with lazy set to false. This option tells Hibernate to retrieve the author object together with our book object. However, most of the time you will use lazy set to true, this is also the default value.

Oct 17, 2008

Fast and easy Hibernate example-tutorial (Part 1)

This tutorial tries to provide fast and easy instructions on getting started with Hibernate. You can download Hibernate from http://www.hibernate.org.
I won't explain how to make Java project with eclipse or netbeans, it is beyond the scope of this text.

Hibernate is an open-source ORM(object relational mapping) library. It is one of the basic tools for fast and reliable java application development. Hibernate is published under LGPL license that allows you to use it in both open-source and commercial projects.

The fastest way to learn something new is with examples. So I'll write some basic example for its usage. For this exercise I'll use PostgreSQL as my database server. It doesn't matter so much, changing to another type is easy from the Hibernate configuration file.

Lets have database called 'example' with table 'books'. Books will have 3 columns - id, title and author.
Here is our persistent class - I'll call it Book


public class Book {
private Integer id;

private String title;

private String author;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}



And this would be our mapping xml file Book.hbm.xml:


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<hibernate-mapping>

<class name="Book" table="books">

<id name="id" column="id">

<generator class="native"/>

</id>

<property name="title" column="title" type="java.lang.String" />

<property name="author" column="author" type="java.lang.String" />

</class>

</hibernate-mapping>



This is the Hibernate configuration file :

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

<property name="hibernate.connection.url">jdbc:postgresql://localhost/example</property>

<property name="hibernate.connection.username">username</property>

<property name="hibernate.connection.password">secret</property>

<property name="connection.pool_size">1</property>

<property name="show_sql">true</property>

<mapping resource="Book.hbm.xml" />

</session-factory>

</hibernate-configuration>




Now we are ready to test what we've done. Lets make simple text class BookExercise.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Book firstBook = new Book();
firstBook.setId(1);
firstBook.setTitle("Our first book title");
firstBook.setAuthor("Our Author");

Book secondBook = new Book();
secondBook.setId(2);
secondBook.setTitle("Second book title");
secondBook.setAuthor("Our Author");

Transaction tx = session.beginTransaction();

session.saveOrUpdate(firstBook);
session.saveOrUpdate(secondBook);

tx.commit();

session.close();
sessionFactory.close();
}
}


Now you must have two records in your books table. To view them you can try to change the exercise class this way:


import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Criteria criteria = session.createCriteria(Book.class);
List books = criteria.list();

Iterator it = books.iterator();
while(it.hasNext()) {
Book book = (Book) it.next();
System.out.println("Book: " + book.getTitle() + " with author: " + book.getAuthor());
}

session.close();
sessionFactory.close();
}
}

Oct 16, 2008

Laziness

I haven’t written anything to my blog for a while. I am not exactly devoted blogger, so this is easy to explain. And recently I am too lazy to do anything. Or maybe I am just tired.

Popular Posts