Hibernate Sample Project With Scala And Gradle

Do you like this?

Summary:
This short tutorial shows you the steps to create a Scala project which uses Hibernate to connect to MySQL database using Gradle as the build tool.


Content:

Please look at the article How to set up Scala projects in Eclipse with Gradle if you don't know how to do so.

The build.gradle file for this project is as follows.

apply plugin: 'scala'
apply plugin: 'eclipse'

repositories{
    mavenCentral()
    mavenLocal()
}

dependencies{
    compile 'org.slf4j:slf4j-api:1.7.5'
    compile "org.scala-lang:scala-library:2.11.2"
    compile 'edu.uci.ics:crawler4j:3.4'
	compile 'mysql:mysql-connector-java:5.1.9'
	compile 'org.hibernate:hibernate-entitymanager:3.3.2.GA'
	compile 'dom4j:dom4j:1.6.1'
	compile 'commons-logging:commons-logging:1.1.1'
	compile 'commons-collections:commons-collections:3.2.1'
	compile 'cglib:cglib:2.2'
	compile 'javax.transaction:jta:1.1'

    testCompile "junit:junit:4.11"
}

task run(type: JavaExec, dependsOn: classes) {
    main = 'Test'
    classpath sourceSets.main.runtimeClasspath
    classpath configurations.runtime
}
Under the folder src/main/resources, create a file called hibernate.cfg.xml.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<mapping class="models.Link"></mapping>
	</session-factory>
</hibernate-configuration>
Under src/main/scala, create a file named HibernateUtil.scala
import org.hibernate.cfg.AnnotationConfiguration
import org.hibernate.SessionFactory

object HibernateUtil {
  private val sessionFactory = buildSessionFactory

  private def buildSessionFactory: SessionFactory = {
    try {
      // Create the SessionFactory from hibernate.cfg.xml
      return new AnnotationConfiguration().configure().buildSessionFactory();

    } catch {
      case ex: Throwable => {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
      }
    }
  }

  def getSessionFactory = sessionFactory


  def shutdown {
    // Close caches and connection pools
    getSessionFactory.close();
  }
}
Under the same folder src/main/scala, create a folder models and a file Links.scala under it.
import javax.persistence._

@Entity
@Table(name = "links")
class Link(url: String) {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  var id: Int = _

  var status: String = _

  override def toString = id + ")" + url
}
Finally under src/main/scala, create a file named Test.scala
import org.hibernate._
import models.Link

object Test extends App{

		val session: Session = HibernateUtil.getSessionFactory.openSession();

		session.beginTransaction();
		val link= new Link("abc")
		link.status = "1"
		session.save(link);
		session.getTransaction().commit();
		println("FINISHED")
}
Next you need to create a sample table in the database schema test for MySQL.

CREATE TABLE IF NOT EXISTS `links` (
`id` bigint(20) NOT NULL,
  `url` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
  `status` varchar(55) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0 ;

ALTER TABLE `links` ADD PRIMARY KEY (`id`);
 
ALTER TABLE `links`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=0;
In the console of your project root directory, run gradle run

 
comments powered by Disqus