Thursday, January 15, 2015

Simple Eclipse Maven Hibernate Setup

create a JPA project using

pom.xml

<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>[4.2.6,4.2.9]</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
</dependencies>


src/hibernatecfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!--  Database connection settings  -->
  <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
  <property name="connection.username">csfox</property>
  <property name="connection.password">password</property>
  <property name="dialect">org.hibernate.dialect.OracleDialect</property>
  <!--  Echo all executed SQL to stdout  -->
  <property name="show_sql">true</property>
  <!--  Drop and re-create the database schema on startup  -->
  <property name="hbm2ddl.auto">create-drop</property>
  <mapping class="hibernate.Message"/>
 </session-factory>
</hibernate-configuration>

sample java table

@Entity
public class MyTable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column(nullable = false)
    String value;

run java 
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder();
        serviceRegistryBuilder.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = serviceRegistryBuilder.buildServiceRegistry();
        SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
        Transaction tx = session.beginTransaction();
        session.persist(object);
        tx.commit();
 List<MyTable > list = (List<MyTable>) session.createQuery(
            "from MyTable").list();
        session.close();


No comments:

Post a Comment