Monday, May 12, 2014

Create Hibernate Project with annotation hibernate + mysql

Create a maven project and build it to support the hibernate

1. create maven project

execute below command
you need to have maven in your system

mvn archetype:generate -DgroupId=com.mkyong -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

eg:

C:\example\Tutorial\Hibernate>mvn archetype:generate -DgroupId=com.mkyong -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 2.0 K
B/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 1.3
KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.mkyong
[INFO] Parameter: packageName, Value: com.mkyong
[INFO] Parameter: package, Value: com.mkyong
[INFO] Parameter: artifactId, Value: HibernateExample
[INFO] Parameter: basedir, Value: C:\example\Tutorial\Hibernate
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\example\Tutorial\Hibernate\HibernateExample
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.246s
[INFO] Finished at: Fri May 09 11:22:11 IST 2014
[INFO] Final Memory: 6M/16M
[INFO] ------------------------------------------------------------------------
C:\example\Tutorial\Hibernate>


This will create simple maven project with 
/HibernateExample/src/main/java/com/mkyong/App.java 
/HibernateExample/src/test/java/com/mkyong/AppTest.java



---------  pom will have---
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.mkyong
  HibernateExample
  jar
  1.0-SNAPSHOT
  HibernateExample
  http://maven.apache.org
  
 
  
   
      junit
      junit
      3.8.1
      test
   
    
 
  


----------------
you can refer below also for with oracle
http://www.mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11g-example-xml-mapping/


we need to create table

let's create a table name with "Stock" . below will be sql

DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



2. then we need to create a java class to map table, hibernate mapping classs

package com.mkyong.common;

import static javax.persistence.GenerationType.IDENTITY;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements Serializable {

/**
*/
private static final long serialVersionUID = 7029806795746254329L;
private Integer stockId;
private String stockCode;
private String stockName;

public Stock() {

}

public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return stockId;
}

public void setStockId(Integer stockId) {
this.stockId = stockId;
}

@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return stockCode;
}

public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}

@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return stockName;
}

public void setStockName(String stockName) {
this.stockName = stockName;
}
}



------------------------------------------

3. We need a Hibernate utill class to create hibernate session factory 

-------------------

package com.mkyong.util;

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

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();
 
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml - for XML mapping
// return new Configuration().configure().buildSessionFactory();
// for annotations
return new Configuration().configure().buildSessionFactory();
} 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);
}
}
 
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
 
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}


-----------------------


to make the hibernate configuration we need hibernate configuration file.

/HibernateExample/src/main/resources/hibernate.cfg.xml

-----------------------------------


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
  com.mysql.jdbc.Driver
  jdbc:mysql://localhost:3306/mkyong
  root
  root123
  org.hibernate.dialect.MySQLDialect
 
  true
 
 


-------------------------------


4. we need to add dependency to the pom file. without dependency code even compile.]
this is first most steps.
you can start project with adding dependency
/HibernateExample/pom.xml

--------------
org.hibernate
hibernate-core
4.1.4.Final


org.hibernate.common
hibernate-commons-annotations
4.0.1.Final


mysql
mysql-connector-java
5.1.9



javassist
javassist
3.12.1.GA

----------------------------------------------------

pom.xml willl be finally looks like this
----------------------------------------------------------


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.mkyong
HibernateExample
jar
1.0-SNAPSHOT
HibernateExample
http://maven.apache.org


junit
junit
3.8.1
test

org.hibernate
hibernate-core
4.1.4.Final


org.hibernate.common
hibernate-commons-annotations
4.0.1.Final


mysql
mysql-connector-java
5.1.9



javassist
javassist
3.12.1.GA



org.codehaus.mojo
exec-maven-plugin
1.2.1
java
com.mkyong.App2
foo
bar



------------------------------------------------------------------


org.codehaus.mojo
exec-maven-plugin
1.2.1
java
com.mkyong.App2
foo
bar



this is to run main method
-------------------------------------------------------

5. Finally we need to test class to test our hibernate project. We create App2.java class

---------------------

package com.mkyong;

import org.hibernate.Session;

import com.mkyong.common.Stock;
import com.mkyong.util.HibernateUtil;

public class App2 {
public static void main(String[] args) {
System.out.println("Maven + Hibernate + MySQL");
Session session = HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();
Stock stock = new Stock();

stock.setStockCode("4716");
stock.setStockName("SN4716");

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


-----------------------









No comments:

Post a Comment