JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Many-to-One Relationship in Hibernate Mappings – Example

September 28, 2008 by JavaBeat Leave a Comment

This example program demonstrates how to write the many-to-one accociations using the hibernate mapping files.

Book.java

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
package hibernate;
 
import java.io.Serializable;
 
public class Book implements Serializable{
	private long id;
	private String title;
	private Publisher publisher;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Publisher getPublisher() {
		return publisher;
	}
	public void setPublisher(Publisher publisher) {
		this.publisher = publisher;
	}
 
}

package hibernate; import java.io.Serializable; public class Book implements Serializable{ private long id; private String title; private Publisher publisher; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } }

Publisher.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package hibernate;
 
import java.io.Serializable;
 
public class Publisher implements Serializable{
	private long id;
	private String name;
	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;
	}
 
}

package hibernate; import java.io.Serializable; public class Publisher implements Serializable{ private long id; private String name; 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; } }

HibernateExample.java

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
package hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
/**
 * source : www.javabeat.net
 */
public class HibernateExample {
    public static void main(String args[]){
        Configuration configuration = new Configuration();
        SessionFactory  sessionFactory = configuration.configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Publisher publisher = new Publisher();
        publisher.setName("First");
        session.save(publisher);
        transaction.commit();
        transaction = session.beginTransaction();
        Book book = new Book();
        book.setTitle("Test");
        book.setPublisher(publisher);
        session.save(book);
        transaction.commit();
        session.close();
    }
}

package hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; /** * source : www.javabeat.net */ public class HibernateExample { public static void main(String args[]){ Configuration configuration = new Configuration(); SessionFactory sessionFactory = configuration.configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Publisher publisher = new Publisher(); publisher.setName("First"); session.save(publisher); transaction.commit(); transaction = session.beginTransaction(); Book book = new Book(); book.setTitle("Test"); book.setPublisher(publisher); session.save(book); transaction.commit(); session.close(); } }

Book.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="hibernate.Book" table="Book">
        <id name="id" column="id" type="java.lang.Long" >
        	<generator class="increment"/>
        </id>
        <property name="title" column="title" type="java.lang.String"/>
        <many-to-one name="publisher" class="hibernate.Publisher" column="publisher"/>
    </class>
</hibernate-mapping>

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <class name="hibernate.Book" table="Book"> <id name="id" column="id" type="java.lang.Long" > <generator class="increment"/> </id> <property name="title" column="title" type="java.lang.String"/> <many-to-one name="publisher" class="hibernate.Publisher" column="publisher"/> </class> </hibernate-mapping>

Publisher.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="hibernate.Publisher" table="Publisher">
        <id name="id" column="id" type="java.lang.Long">
        	<generator class="increment"/>
        </id>
        <property name="name" column="name" type="java.lang.String"/>
    </class>
</hibernate-mapping>

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <class name="hibernate.Publisher" table="Publisher"> <id name="id" column="id" type="java.lang.Long"> <generator class="increment"/> </id> <property name="name" column="name" type="java.lang.String"/> </class> </hibernate-mapping>

hibernate.cfg.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
 
<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/SampleDB</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 
        <!-- Mapping files -->
        <mapping  resource="Publisher.hbm.xml"/>
        <mapping  resource="Book.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/SampleDB</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Mapping files --> <mapping resource="Publisher.hbm.xml"/> <mapping resource="Book.hbm.xml"/> </session-factory> </hibernate-configuration>

Filed Under: Hibernate Tagged With: hibernate mappings

Configure MySql Database With Hibernate Mappings

July 29, 2008 by Krishna Srinivasan Leave a Comment

Configure MySql Database

Configuring MySql database with hibernate is the same as with other databasses. The only difference will be connection url and the database dialect to be specified in the configuration file. This tips provides a basic example configuration file for configuaring the MySql with hibernate. But it doesn’t explain you installing the MySql database. If you are looing for installing MySql database please read it here : http://dev.mysql.com/downloads/

also read:

  • Introduction to Hibernate
  • Hibernate Interview Questions
  • Interceptors in Hibernate
  • Hibernate Books

Sample URL is jdbc:mysql://localhost:3306/SampleDB. In this URL port 3306 is default for the mysql database. If you are not specifying that in the URL, it will assume the port is 3306.localhost can be replaced with your system IP address and machine name.SampleDB is the database or catelog name you have created. Every session factory can have only one database. if you want to use multiple database, create multiple session factory with different database names.

org.hibernate.dialect.MySQLDialect (Read: List of Hibernate Dialects) is the dialect name for MySQL database. Each database has its own dialect declared in the hibernate package.

[code lang=”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>
<!– Database connection settings –>
<property name=’connection.driver_class’>com.mysql.jdbc.Driver</property>
<property name=’connection.url’>jdbc:mysql://localhost:3306/SampleDB</property>
<property name=’connection.username’>root</property>
<property name=’connection.password’>root</property>

<!– JDBC connection pool (use the built-in) –>
<property name=’connection.pool_size’>1</property>

<!– SQL dialect –>
<property name=’dialect’>org.hibernate.dialect.MySQLDialect</property>

<!– Echo all executed SQL to stdout –>
<property name=’show_sql’>true</property>

<!– Mapping files –>
<mapping resource=’Author.hbm.xml’/>
</session-factory>
</hibernate-configuration>
[/code]

Filed Under: Hibernate Tagged With: hibernate mappings, MySQL

Collection Mapping in Hibernate : one-to-many

July 26, 2008 by Krishna Srinivasan Leave a Comment

one-to-many class mapping

This article explains how to map two classes in collection mapping. In this example one Author object has the list of Book objects. Both the classes are mapped and will be inserted together into the database. Here this example uses Bag as the collection type. Other collection types available are Set,List,Array. Look into the example programs for more detail.

Author.java

[code lang=”java”]

package javabeat.net.hibernate;

/**
* source : www.javabeat.net
*/
import java.util.List;

public class Author {
private long id;
private String name;

public String getName() {
return name;
}

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

public List<book> getBooks() {
return books;
}

public void setBooks(List<book> books) {
this.books = books;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}
private List<book> books;
}

[/code]

Book.java

[code lang=”java”]
package javabeat.net.hibernate;

/**
* source : www.javabeat.net
*/
public class Book {
private long id;
private String name;

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;
}
}
[/code]

JavaBeatHibernateExample

[code lang=”java”]
package javabeat.net.hibernate;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
* source : www.javabeat.net
*/
public class JavaBeatHibernateExample {
public static void main(String args[]) {
Configuration configuration = new Configuration();
// configuring hibernate
SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
Book book1 = new Book();
book1.setName("Java Book");

List<book> list = new ArrayList<book>();
list.add(book1);

Author author = new Author();
author.setName("First Author");
author.setBooks(list);
session.save(author);
tx.commit();;
session.flush();
session.close();
}
}
[/code]

also read:

  • Introduction to Hibernate
  • Hibernate Interview Questions
  • Interceptors in Hibernate
  • Hibernate Books

Author.hbm.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="javabeat.net.hibernate.Author" table="Author">
<id name="id" column="id" type="java.lang.Long" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" column="name" type="java.lang.String"/>
<bag name="books" cascade="all" >
<key column="id"/>
<one-to-many class="javabeat.net.hibernate.Book"/>
</bag>
</class>
<class name="javabeat.net.hibernate.Book" table="Book">
<id name="id" column="id" type="java.lang.Long" unsaved-value="0" >
<generator class="increment"/>
</id>
<property name="name" column="name" type="java.lang.String"/>
</class>
</hibernate-mapping>
[/code]

hibernate.cfg.xml

[code lang=”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="connection.url">jdbc:derby://localhost:1527/SampleDB
</property>
<property name="connection.username">root
</property>
<property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver
</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect
</property>
<property name="connection.password">root
</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name="current_session_context_class">thread
</property>
<property name="hibernate.show_sql">true
</property>
<mapping resource="javabeat/net/hibernate/Author.hbm.xml"/>
</session-factory>
</hibernate-configuration>
[/code]

Filed Under: Hibernate Tagged With: hibernate mappings

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved