eclipse project structure
public class Employee {
private int id;
private String firstName;
private String lastName;
private String telephone;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3. EmployeeC.java
package com.test.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name="Employee",
uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class EmployeeAnnotation {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID", nullable=false, unique=true, length=11)
private int id;
@Column(name="firstName", length=20, nullable=true)
private String firstName;
@Column(name="lastName", length=20, nullable=true)
private String lastName;
@Column(name="telephone", length=20, nullable=true)
private String telephone;
@Column(name="email", length=20, nullable=true)
private String email;
}
4. log4j.properties
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
5. Hibernate Util class (HibernateUtil.java)
package com.test.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.test.hibernate.model.EmployeeAnnotation;
public class HibernateUtil {
// XML based configuration
private static SessionFactory sessionFactory;
// Annotation based configuration
private static SessionFactory sessionAnnotationFactory;
// Property based configuration
private static SessionFactory sessionJavaConfigFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
// Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class",
"com.mysql.jdbc.Driver");
props.put("hibernate.connection.url",
"jdbc:mysql://localhost/nadhu");
props.put("hibernate.connection.username", "root");
props.put("hibernate.connection.password", "knmuni");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
// we can set mapping file or class with annotation
configuration.addAnnotatedClass(EmployeeAnnotation.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null)
sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
public static SessionFactory getSessionJavaConfigFactory() {
if (sessionJavaConfigFactory == null)
sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
}
6 . Main class (HibernateMain .java) --- XML
package com.test.hibernate.main;
import org.hibernate.Session;
import com.test.hibernate.model.Employee;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
//Get Session
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
//terminate session factory, otherwise program won't end
HibernateUtil.getSessionFactory().close();
}
}
7. Main Class (HibernateMainAnnotation.java) --- Annotation
package com.test.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.test.hibernate.model.EmployeeAnnotation;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMainAnnotation {
public static void main(String[] args) {
EmployeeAnnotation emp = new EmployeeAnnotation();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
// Get Session
SessionFactory sessionFactory = HibernateUtil
.getSessionAnnotationFactory();
Session session = sessionFactory.getCurrentSession();
// start transaction
session.beginTransaction();
// Save the Model object
session.save(emp);
// Commit transaction
session.getTransaction().commit();
// terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
8. Main Class (HibernateMainJavaConfig.java) --- JavaConfig
package com.test.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.test.hibernate.model.EmployeeAnnotation;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMainJavaConfig {
public static void main(String[] args) {
EmployeeAnnotation emp = new EmployeeAnnotation();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
//Get Session
SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
Session session = sessionFactory.getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
//terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
9.Employee.hbm.xml
10.hibernate-annotation.cfg.xml
11.hibernate.cfg.xml
12.pom.xml
1. SQL Script (MySQL)
CREATE TABLE employee (
id int not null auto_increment,
firstname varchar(20),
lastname varchar(20),
telephone varchar(20),
email varchar(30),
primary key(id)
);
id int not null auto_increment,
firstname varchar(20),
lastname varchar(20),
telephone varchar(20),
email varchar(30),
primary key(id)
);
2. Model Classes(Employee.java)
package com.test.hibernate.model;public class Employee {
private int id;
private String firstName;
private String lastName;
private String telephone;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3. EmployeeC.java
package com.test.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name="Employee",
uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class EmployeeAnnotation {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID", nullable=false, unique=true, length=11)
private int id;
@Column(name="firstName", length=20, nullable=true)
private String firstName;
@Column(name="lastName", length=20, nullable=true)
private String lastName;
@Column(name="telephone", length=20, nullable=true)
private String telephone;
@Column(name="email", length=20, nullable=true)
private String email;
}
4. log4j.properties
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
5. Hibernate Util class (HibernateUtil.java)
package com.test.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.test.hibernate.model.EmployeeAnnotation;
public class HibernateUtil {
// XML based configuration
private static SessionFactory sessionFactory;
// Annotation based configuration
private static SessionFactory sessionAnnotationFactory;
// Property based configuration
private static SessionFactory sessionJavaConfigFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
// Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class",
"com.mysql.jdbc.Driver");
props.put("hibernate.connection.url",
"jdbc:mysql://localhost/nadhu");
props.put("hibernate.connection.username", "root");
props.put("hibernate.connection.password", "knmuni");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
// we can set mapping file or class with annotation
configuration.addAnnotatedClass(EmployeeAnnotation.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null)
sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
public static SessionFactory getSessionJavaConfigFactory() {
if (sessionJavaConfigFactory == null)
sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
}
6 . Main class (HibernateMain .java) --- XML
package com.test.hibernate.main;
import org.hibernate.Session;
import com.test.hibernate.model.Employee;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
//Get Session
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
//terminate session factory, otherwise program won't end
HibernateUtil.getSessionFactory().close();
}
}
7. Main Class (HibernateMainAnnotation.java) --- Annotation
package com.test.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.test.hibernate.model.EmployeeAnnotation;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMainAnnotation {
public static void main(String[] args) {
EmployeeAnnotation emp = new EmployeeAnnotation();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
// Get Session
SessionFactory sessionFactory = HibernateUtil
.getSessionAnnotationFactory();
Session session = sessionFactory.getCurrentSession();
// start transaction
session.beginTransaction();
// Save the Model object
session.save(emp);
// Commit transaction
session.getTransaction().commit();
// terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
8. Main Class (HibernateMainJavaConfig.java) --- JavaConfig
package com.test.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.test.hibernate.model.EmployeeAnnotation;
import com.test.hibernate.util.HibernateUtil;
public class HibernateMainJavaConfig {
public static void main(String[] args) {
EmployeeAnnotation emp = new EmployeeAnnotation();
emp.setFirstName("Rama");
emp.setLastName("Krishna");
emp.setEmail("abc@abc.com");
emp.setTelephone("123456");
//Get Session
SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
Session session = sessionFactory.getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
//terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
9.Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.hibernate.model.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="firstname" type="string"/>
<property name="lastName" column="lastname" type="string"/>
<property name="telephone" column="telephone" type="string"/>
<property name="email" column="email" type="string"/>
</class>
</hibernate-mapping>
10.hibernate-annotation.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/nadhu</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">knmuni</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Mapping with model class containing annotations -->
<mapping class="com.test.hibernate.model.EmployeeAnnotation"/>
</session-factory>
</hibernate-configuration>
11.hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/nadhu</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">knmuni</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">1</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL,
Oracle etc Hibernate 4 automatically figure out Dialect from Database Connection
Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- mapping file, we can use Bean annotations too -->
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
12.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateDemo</groupId>
<artifactId>HibernateDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
1 comment:
wow nice blog
java j2ee training course contents | java j2ee training institutes in chennai | java j2ee training | java training in chennai velachery
Post a Comment