December 7, 2005

This pic explains why ruby on rails.

Posted in Java, Uncategorized at 9:31 am by Frank

I always choose python as my script language but ruby on rails is very hot these days, so many people turn their head to ruby, me included. Some guys said that ruby is more oo then python. After reading a few ruby docs, I found that ruby is kinda like basic, use end to mark the ending of a block, and its syntax seems very weird to me. So I didn’t go with it any deeper. But this picture seems very funny and persuadable, I can’t help looking through ruby docs again.

November 27, 2005

Together2006 now supports eclipse3.11

Posted in brief, Java at 11:45 am by Frank

Yesterday when I download the together 2006 from borland site I found that the file is much larger than the previous together2006, so I guess it’s been updated. After 30 minutes I finished downloading it but when I tried to install it I failed again and again. I unzipped the eclipse 3.1 and told the location to together installer, everytime I can’t find any together stuff from inside of eclipse IDE. I tried eclipse 3.1, 3.11, then 3.1 again, and everytime the together features would never show to me. Eclipse compatibility is really a big problem, many plug-ins is not version-exchangable. I decided to try the last time, I would give up if I fail again. The last time during the installation, I noticed some useful hints on a dialog which said it’s only for eclipse 3.11 and to use the eclipse packaged with the installation program is recommended. So I didn’t specify any other eclipse, and I succeeded this time in the end.

Eclipse is very good, and it’s not slower then vs2005. But the version problem is often frustrating, especially when trying to add a plug-in to it. And toghether 2006 now is stronger than the last version I used. Last time when I try to generate a sequence diagram by it, it stuck in the middle and eclipse got unresponsable. I had to kill it from the task manager. But when I tried to use it again today, after some smooth progressbars, I got the amazing sequence diagram. Together is really powerful.

November 22, 2005

Hibernate basic(2)

Posted in Java at 2:37 am by Frank

Listing a table
Listing a table does “select * from tablexxx” thing. In hibernate we can create a query with a query string “from User” and then call query.list. It return a collection of users, as shown below.
    Query q=session.createQuery(“from User”);
    List l=q.list();

    Iterator it=l.iterator();
    while(it.hasNext())
        System.out.println(((User)it.next()).toString());

Querying data
Hibernate use its only query language named HSQL to query data from db. I made a very simple query with it:
    Query q = session.createQuery(“select u from User as u where u.name>? and u.age<?”);
    q.setString(0,”Hello”);
    q.setInteger(1,80);
    List l=q.list();

    Iterator it = l.iterator();
    while(it.hasNext())
    System.out.println(((User)it.next()).toString());

Deleting an object
Use session.delete(object) to delete an object from the database table:
    Query q=session.createQuery(“select u from User as u where u.name=?”);
    q.setString(0,”Jack”);

    Iterator it=q.list().iterator();
    Transaction tx=session.beginTransaction();
    while(it.hasNext())
        session.delete(it.next());
    tx.commit();

Modifying data
In a session, when you modified an obj, just use session.flush() to update it. If an object is modified outside of a session, use session.update() to save the modification. Codes below demonstrate modifying data inside a session using flush:
Query q=session.createQuery(“select u from User as u where u.name>?”);
q.setString(0,”Hello”);
Iterator it=q.list().iterator();

Transaction tx=session.beginTransaction();
while(it.hasNext())
{
    User user=(User)(it.next());
    user.setName(“Could”);
    session.flush();
}
tx.commit();

Hibernate basic(1)

Posted in Java at 2:22 am by Frank

I want to get some impression of hibernate these days. I worked with it and do some basic stuff such as Adding, Listing, Querying, Modifying, and deleting data. I worked with only one table in an HSQLDB database to do these basic things, coz I want to get a full impression of all the database operations as soon as possible. In fact, it took me only couple of hours.

I choose HSQLDB 1.71 as database. It’s very light-weight, and it can be used as a desktop db and needn’t a huge server running and sucking up so much memory. I like fat-file db.

Creating a new database in hsql is only need to connect to a unexist database with username “sa” and an empty password. HSQL will create a db for you if no db is found. I use squirrelsql to connect my database. It’s an useful jdbc client tool. I create a table User with the following sql:
CREATE TABLE USER (
    user_id CHAR(32) NOT NULL PRIMARY KEY,
    name VARCHAR(16) NOT NULL,
    sex CHAR(1),
    age INT
)
This sql is from here, it’s a hibernate torurial in traditional Chinese. I referrenced it. It uses MYSQL and hb 2.1, I use hsqldb and hibernate 3.05.

It’s very tedious to write cfg.xml and hbm.xml files, and it’s a waste of time. Hibernate Tools does now do these annoying works for us. Hibernate tools page has 2 flash files demonstrat how to use the tools. I worked after it and found it really useful.

Firstly, build the hibernate.cfg.xml. My project got the file like this:
<?xml version=”1.0″ encoding=”utf-8″?>
<!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.cglib.use_reflection_optimizer”>true</property>
        <property name=”hibernate.connection.driver_class”>org.hsqldb.jdbcDriver</property>
        <property name=”hibernate.connection.url”>JDBC:HSQLDB:F:\My_Java\Projects_Eclipse\HibernateBasic\db\db</property>
        <property name=”hibernate.connection.username”>sa</property>
        <property name=”hibernate.dialect”>org.hibernate.dialect.HSQLDialect</property>
        <property name=”hibernate.show_sql”>true</property>
        <mapping resource=”basichibernate/User.hbm.xml” />
        <mapping resource=”basichibernate/Event.hbm.xml”/>
    </session-factory>
</hibernate-configuration>
The line ” true ” is added by me manually to tell hibernate to show sql. Hibernate Tools doesn’t add it for me.

And then use Hibernate Artifact Generation to renerate java source files and hbm.xml files. I have only one table USER here so I got only one java source file User.java, which is showing below:
package basichibernate;

/**
* User generated by hbm2java
*/

public class User implements java.io.Serializable
{
    private static final long serialVersionUID = 1L;
    private String userId;
    private String name;
    private Character sex;
    private Integer age;
    // Constructors
    /** default constructor */
    public User()
    {
    }

    /** constructor with id */
    public User(String userId)
    {
        this.userId = userId;
    }

    // Property accessors
    public String getUserId()
    {
        return this.userId;
    }
    public void setUserId(String userId)
    {
        this.userId = userId;
    }
    public String getName()
    {
        return this.name;
    }

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

    public Character getSex()
    {
        return this.sex;
    }

    public void setSex(Character sex)
    {
        this.sex = sex;
    }

    public Integer getAge()
    {
        return this.age;
    }

    public void setAge(Integer age)
    {
        this.age = age;
    }

    public String toString()
    {
        return “id:” + userId + “n” + “    name:” + name + “n” + “    age:”
                + age + “n” + “    sex:” + sex.toString() + “n”;
    }

}
toString() method is overrided by myself.
And the corresponding hbm file User.hbm.xml is also generated for us:
<?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>
<!–
        Auto-generated mapping file from
        the hibernate.org cfg2hbm engine
–>
    <class name=”basichibernate.User” table=”USER”>
        <id name=”userId” type=”string”>
            <column name=”USER_ID” length=”32″ />
            <generator class=”uuid.hex” />
        </id>
        <property name=”name” type=”string”>
            <column name=”NAME” length=”16″ not-null=”true” />
        </property>
        <property name=”sex” type=”character”>
            <column name=”SEX” length=”1″ />
        </property>
        <property name=”age” type=”integer”>
            <column name=”AGE” />
        </property>
    </class>
</hibernate-mapping>

The line “<generator class=”uuid.hex” />” is modified manually.

In my conclusion, simple use of hibernate need only 3 steps, which can be seen in my codes later. The 3 steps are:
1. Obtain a session object. One way to do this can be done in these 2 lines of code:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
2. Get Objects from session and do your things with them.
3. Close the session and sessionfactory.
org.hibernate.* org.hibernate.cfg.* always need to be imported when using hibernate.

Adding new data
My class AddNew.java is show below. It inserts 100 users in the user table. I write a simple method RandomName() to return a random string which is 5~25 letters in length and with its first letter capitalized.
package basichibernate;

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;

public class AddNew
{
    public static void main(String[] args)
    {
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session session=sf.openSession();
        Transaction tx=session.beginTransaction();
    
        Random r=new Random();
    
        //insert 100 users in the user table
        for(int i=0;i<100;i++)
        {
            User user=new User();
            user.setAge(r.nextInt(100)+10);
            user.setName(RandomName());
            user.setSex(‘M’);
            session.save(user);
        }
        tx.commit();
        session.close();
        sf.close();
        System.out.println(“done. inserted 100 users”);
    }

    private static String RandomName()
    {
        Random r = new Random();
        int len = r.nextInt(20) + 5;// set length of name, 5~25 chars
        String name = “”;
        for (int i = 0; i < len; i++)
        {
            if (i == 0)
                name = (name + (char) (r.nextInt(25) + 97)).toUpperCase();
            else
                name = name + (char) (r.nextInt(25) + 97);
        }
        return name;
    }
}

Follow

Get every new post delivered to your Inbox.