Clouds
Home

Hibernate 2.0 Introduction

Hibernate Mapping Declaration

Hibernate Development Code

Hibernate Generator

Inheritence Mapping

Hibernate Development Code


User.java


package persist;
public class User {
    private Long id;
    private String username;
    private String password;
    private String role;

    public User(){}

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

    public String getPassword() {return password;}
    public void setPassword(String password) {this.password = password;}

    public String getUsername() {return username;}
    public void setUsername(String username) {this.username = username;}

    public String getRole() {return role;}
    public void setRole(String role) {this.role = role;}
}


User.hbm.xml


<hibernate-mapping>
    <class name="persist.User" table="USER_TABLE">
      <id name="id" column="USER_ID">
        <generator class="native"/>
      </id>
      <property name="username" type="String" column="UNAME"/>
      <property name="password" type="String" column="PWD"/>
      <property name="role" type="String" column="UROLE"/>
    </class>
</hibernate-mapping>


Hibernate.properties


hibernate.connection.driver_class =com.mysql.jdbc.Driver
hibernate.connection.url= jdbc:mysql://localhost:3306/databaseName
hibernate.connection.username =database username
hibernate.connection.password =database password
hibernate.dialect =org.hibernate.dialect.MySQLDialect


HibernateUtil.java


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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
      try {
        // Create the SessionFactory from hibernate.cfg.xml
        sessionFactory = new Configuration().configure().buildSessionFactory();
      } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        throw new ExceptionInInitializerError(ex);
      }
    }

    public static SessionFactory getSessionFactory() { return sessionFactory; }
}


PersisUserToDatabase.java


import org.hibernate.Session;
import java.util.Date;
import util.HibernateUtil;
import persist.User;
public class PersistUserToDatabase {
    public static void main(String[] args) {
      Session session = HibernateUtil.getSessionFactory().getCurrentSession();

      session.beginTransaction();

      User user = new user();
      user.setName("user1");
      user.setPassword("ABC1234df");
      user.setRole("Admin");

      session.save(user);
      session.getTransaction().commit();
    }
}


<<<< PREVIOUS: Hibernate Mapping Declaration          NEXT: Hibernate Generator >>>>


Home Clouds