czwartek, 22 października 2015

Hibernate 5 + Maven + MySQL - "Hello World" app in Java

This is short example of hello world app in java with hibernate 5 and maven. It doesn't describe the details, but might be useful if you just want to see the working code. It shows example maven's pom.xml, hibernate configuration file and code for creating one table with one record.

1. Creating project with Maven

in your console run command:
mvn archetype:generate -DgroupId="com.blogspot.aknowakowski
ski" -DartifactId="Hibernate-Hello-World" -DarchetypeArtifactId="maven-archetype-quickstart"


(you can confirm suggested 1.0-SNAPSHOT version if maven asks)

Edit pom.xml and add dependencies for hibernate and for mysql connector:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.2.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

Add exec plugin which will make running app easier:
<build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <mainClass>com.blogspot.aknowakowski.App</mainClass>
                    <cleanupDaemonThreads>false</cleanupDaemonThreads>
                </configuration>
            </plugin>
        </plugins>
    </build>
Take a look at line <mainClass>com.blogspot.aknowakowski.App</mainClass>. You need to specify there class with your main method.

Full example of pom.xml:
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blogspot.aknowakowski</groupId>
    <artifactId>Hibernate-Hello-World</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>IOR-Testy</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.2.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <mainClass>com.blogspot.aknowakowski.App</mainClass>
                    <cleanupDaemonThreads>false</cleanupDaemonThreads>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2. Coding

Create entity class:

package com.blogspot.aknowakowski;

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

@Entity
@Table(name="task")
public class Task {
    @Id
    @Column(name="task_id")
    Long id;

    @Column(name="name")
    String name;

    public Task(Long id, String name, String description) {
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public Task() {
    }

    @Column(name="description")
    String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Create hibernate configuration file hibernate.cfg.xml and put it to src/main/resources directory. (Because maven copies files from main/resources to target)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate-hello</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <!-- DB schema will be updated if needed -->
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">false</property>
        <property name="format_sql">false</property>

        <mapping class="com.blogspot.aknowakowski.Task"></mapping>


    </session-factory>
</hibernate-configuration>

Don't forget to add mapping in configuration file (<mapping class="com.blogspot.aknowakowski.Task"></mapping>)


Create class with application main method:

package com.blogspot.aknowakowski;

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

public class App 
{
    public static void main( String[] args )
    {
        SessionFactory sessionFactory;
        sessionFactory = new Configuration()
                .configure() // configures settings from hibernate.cfg.xml
                .buildSessionFactory();

        Session session = sessionFactory.openSession();

        Transaction tx = session.beginTransaction();
        Task task = new Task();
        task.setId(new Long(1));
        task.setName("Hello world task");
        task.setDescription("Hello world task description");
        session.save(task);
        tx.commit();
        session.close();
    }
}

3. Running app

Run commands
mvn package
mvn exec:java

first command will build your app,
second command will run your main method
(you can combine them - mvn package exec:java)

If everything is ok you should see added table and record in the database:

1 komentarz: