HelloWorld with Hibernate-Mysql(XML Mapping)

Build

Refer to this post to build project

Dependencies

pom.xml

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>org.antlr</groupId>
    <artifactId>antlr-complete</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
    <groupId>asm</groupId>
    <artifactId>asm</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>asm</groupId>
    <artifactId>asm-attrs</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.4.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-tools</artifactId>
    <version>5.1.0.Final</version>
</dependency>
<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.5</version>
</dependency>

Database:

Create a database with a name say, test on your mysql


CREATE TABLE `messages` (
 `MESSAGE_ID` bigint(20) NOT NULL AUTO_INCREMENT,
 `MESSAGE_TEXT` varchar(255) DEFAULT NULL,
 `MESSAGE_TIME` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`MESSAGE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Hibernate Util:

Create class HibernateUtil, under com.example package,

package com.example;

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

public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Message Bean:

Create a POJO named Message,

package com.example;

import java.util.Date;

public class Message {
    private Long id;
    private String text;
    private Date createdAt;

    public Message() {
    }

    public Message(String text) {
        this.text = text;
    }

    public Long getId() {
        return id;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
}

HelloWorld:

Create HelloWorld Class under the same package,

package com.example;

import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class HelloWorld {

    public static void main(String[] args) {

        Session session = HibernateUtil.getSessionFactory().openSession();

        Transaction tx = session.beginTransaction();

        // ######################## INSERT ##############################
        Message message = new Message("Hello,World");
        session.save(message);

        // ######################## RETRIEVE  ############################
        List messages = session.createQuery("from Message m order by m.text asc").list();
        System.out.println("##########" + messages.size() + "##########");

        for (Object message1 : messages) {
            Message loadedMsg = (Message) message1;
            System.out.println(loadedMsg.getText());
        }

        // ####################### UPDATE ###############################
        Message updateMessage = (Message) session.get(Message.class, message.getId());
        updateMessage.setText("Hello, Hibernate");

        tx.commit();
        session.close();

        HibernateUtil.shutdown();
    }
}


Hibernate Configuration xml:

Create hibernate config file under resource/hibernate directory,

<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration         PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

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

        <mapping resource="hibernate/Message.hbm.xml"/>

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

Message configuration xml:

Create xml mapping file for Message bean,

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

<hibernate-mapping>

    <class name="com.example.Message" table="MESSAGES">
        <id name="id" column="MESSAGE_ID">
            <generator class="native"/>
        </id>
        <property name="text" column="MESSAGE_TEXT"/>
    </class>

</hibernate-mapping>

Project Structure

ps-2

Run:

Run the HelloWorld and check printed value (should be Hello,World) and updated value(should be Hello, Hibernate) on database.

Advertisements
HelloWorld with Hibernate-Mysql(XML Mapping)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s