Default value in HIBERNATE Database independently

How to initialize Field in Hibernate @Entity without using @Column( columnDefenition=”” ) ?
WHY?
Because columnDefinition is DB dependently option.

Imagine you have some @Entity :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    @Column( name = "insstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime insstmp;// date without time

    @Column( name = "updstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime updstmp;// date without time

    /**
     * We set default value in case if the value is not set yet.
     */

    @PrePersist
    public void prePersist() {

        if ( this.updstmp == null ) {
            // Default value
            this.updstmp = getUpdstmp();
        }
        if ( this.insstmp == null ) {
            // Default value
            this.insstmp = getInsstmp();
        }
    }


    /**
     * Getter.
     *
     * @return the insstmp
     */

    public final DateTime getInsstmp() {

        return insstmp == null ? new DateTime( DateTimeZone.UTC ) : insstmp;
    }

    /**
     * Getter.
     *
     * @return the updstmp
     */

    public final DateTime getUpdstmp() {

        return updstmp == null ? new DateTime( DateTimeZone.UTC ) : updstmp;
    }

MySQL enum in HIBERNATE

How to provide corresponding hibernate Entity and MySQL ENUM type ?

1
enum('Active','Pending','Cancelled','Suspend')

With ANNOTATION :

1
2
@Column(name="status", columnDefinition="enum('Active','Pending','Cancelled','Suspend')")
public String status;

With XML config :

1
2
3
4
5
<property
   name="status"
   column="STATUS"
   type="string"
   not-null="true" />

How to add DATABASE access in Dynamic Web Project ?

We will get such structure :

Add DATABSE in Dynamic Web Projet

Add DATABSE in Dynamic Web Projet

1. Create in your WEB_ROOT these folders: WEB-INF/database
2. Create file “datapase.properties” :

1
2
3
4
5
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc\:postgresql\://109.197.1.1\:5433/yourDB
jdbc.username=yourLogin
jdbc.password=yourPWD
jdbc.showSql=true

3. Create DataSource.xml file – it contains bean “dataSource” and gets value from “datapase.properties” file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>/WEB-INF/database/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>

4. Create Hibernate.xml file – it cares about Spring Transactions, Hibernate Session Factory :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       ">


    <!-- Hibernate transaction manager -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource">
            <ref bean="dataSource" />
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- +1 -->
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <!-- Enable Hibernate's automatic session context management
                   Spring manages the transaction, and it doesn't need of that the session is holding in a
                   hibernate thread.
               <prop key="hibernate.current_session_context_class">thread</prop>
               -->
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>

            </props>
        </property>

        <property name="packagesToScan" value="ru.tomatch.admin.model" />

        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>

        <property name="exposeTransactionAwareSessionFactory">
            <value>false</value>
        </property>


    </bean>
</beans>

5. And last file applicationContext.xml :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   
    <!-- Database Configuration -->
    <import resource="./database/DataSource.xml"/>
    <import resource="./database/Hibernate.xml"/>
 
    <!-- Auto scan the components -->
    <context:component-scan base-package="some.your.package1" />    
    <context:component-scan base-package="some.your.package2" />    

</beans>

Hibernate-SQLite how to add in Java project

http://code.google.com/p/hibernate-sqlite/

1.add repository in the pom.xml file(between the repositories tag)

1
2
3
4
<repository>
  <id>hibernatesqlite-maven</id>
  <url>https://hibernate-sqlite.googlecode.com/svn/trunk/mavenrepo</url>
</repository>

2.add dependency in the pom.xml file(between the dependencies tag)

1
2
3
4
5
6
<!-- hibernate sqlite dialect -->
<dependency>
  <groupId>com.applerao</groupId>
  <artifactId>hibernatesqlite</artifactId>
  <version>1.0</version>
</dependency>

3.modify the hibernate dialect configuration like:

1
<property name="dialect">com.applerao.hibernatesqlite.dialect.SQLiteDialect</property>

4.maven your project and the hibernate-sqlite is ready to use.

Additionally, the version of hibernate used in hibernatesqlite-1.0 is 3.2.6.ga, and if you want to use another version of hibernate, you can exclude the hibernate like this:

1
2
3
4
5
6
7
8
9
10
11
12
<!-- hibernate sqlite dialect -->
<dependency>
        <groupId>com.applerao</groupId>
        <artifactId>hibernatesqlite</artifactId>
        <version>1.0</version>
        <exclusions>
                <exclusion>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate</artifactId>
                </exclusion>
        </exclusions>
</dependency>

and add hibernate dependency like this:

1
2
3
4
5
6
<!-- hibernate jars -->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate</artifactId>
  <version>3.2.7.ga</version>
</dependency>

SelfTraining HOWTO Start HIBERNATE + SQLITE Desctop App ?

Hello.
In this topic i will clarify my experience hot you can start Java Project in ECLIPSE using HIBERNATE 3.5.6-FINAL & SQLite 3.7.2.
FYI : I use SQL Manager in FireFox – This is very simple and fast solution to manage SQLite DB.
Also I have installed maven (m2e) plugin in my Eclipse (4.2 JUNO)
Project builded with jdk 1.7
Continue reading

Hibernate SPRING ~ howto use ANONYMOUS CLASS

1
2
3
4
5
6
7
8
9
10
//anonymous inner classes can only access local variables if they are declared as final  
public Pet getPetById(final String id) {
     return (Pet) getHibernateTemplate().execute(new HibernateCallback() {
             public Object doInHibernate(Session session) {
                     HibernateTemplate ht = getHibernateTemplate();
                     // … can access variable “id”
                     return myPet;
             }
     });
}

HIBERNATE as JPA

persistence.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<persistence -unit name="helloworld">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <!-- Not needed, Hibernate supports auto-detection in JSE
       <class>hello.Message
    -->
  <properties>
      <property name="hibernate.archive.autodetection"
          value="class, hbm"></property>
      <property name="hibernate.show_sql" value="true"></property>
      <property name="hibernate.format_sql" value="true"></property>
      <property name="hibernate.connection.driver_class"
                value="org.hsqldb.jdbcDriver"></property>
      <property name="hibernate.connection.url"
                value="jdbc:hsqldb:hsql://localhost"></property>
      <property name="hibernate.connection.username"
                value="sa"></property>
      <property name="hibernate.c3p0.min_size"
                value="5"></property>
      <property name="hibernate.c3p0.max_size"
                value="20"></property>
      <property name="hibernate.c3p0.timeout"
                value="300"></property>
      <property name="hibernate.c3p0.max_statements"
                value="50"></property>
      <property name="hibernate.c3p0.idle_test_period"
                value="3000"></property>
      <property name="hibernate.dialect"
                value="org.hibernate.dialect.HSQLDialect"></property>
      <property name="hibernate.hbm2ddl.auto" value="create"></property>
  </properties>
</persistence>

Continue reading

Hibernate logback example sample

All thanks http://www.mkyong.com/hibernate/how-to-configure-logging-in-hibernate-logback/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 
 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} %-5level %logger{36} - %msg%n
                </Pattern>
    </encoder>
 </appender>
 
 <appender name="FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>c:/mkyongapp.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
       <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
           </Pattern>
    </encoder>
 
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <FileNamePattern>c:/mkyongapp.%i.log.zip</FileNamePattern>
        <MinIndex>1</MinIndex>
        <MaxIndex>10</MaxIndex>
    </rollingPolicy>
 
    <triggeringPolicy
        class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <MaxFileSize>2MB</MaxFileSize>
    </triggeringPolicy>
 
  </appender>
 
  <logger name="org.hibernate.type" level="ALL" />
  <logger name="org.hibernate" level="DEBUG" />
 
  <root level="INFO">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
 
</configuration>