czwartek, 13 czerwca 2013

Hibernate relation: many to many (bidirectional)

1. Database schema

...

2. Entity class:

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "Country")
public class Country {

   @Id
   @GeneratedValue
   private Long id;

   @Column
   private String name;

   @Column
   private String code;

   @ManyToMany(cascade = {CascadeType.ALL})
   @JoinTable(name = "Jt_Country_Currency",
           joinColumns = {@JoinColumn(name = "CountryId")},
           inverseJoinColumns = {@JoinColumn(name = "CurrencyId")})
   private Set<Currency> currencies;


   public Country(){
   } 
    //getters and setters

}

import javax.persistence.*;
import java.util.Collection;

@Entity
@Table(name = "Currency")
public class Currency {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @Column
    private String code;

    @Column
    private String symbol;

    @ManyToMany(mappedBy = "currencies")
    private Collection<Country> countries;


    public Currency() {
    }
//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?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/test</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>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.Country"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Currency>"/>

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

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        Country country1 = new Country();
        country1.setName("Poland");
        country1.setCode("22");

        Currency currency1 = new Currency();
        currency1.setName("EURO");
        currency1.setSymbol("E");

        Currency currency2 = new Currency();
        currency2.setName("Zloty");
        currency2.setSymbol("PLN");

        Set<Currency> currencySet = new HashSet<Currency>();
        currencySet.add(currency1);
        currencySet.add(currency2);

        country1.setCurrencies(currencySet);

        saveCounty(country1);
    }

    private static void saveCounty(Country country){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(country);
        session.getTransaction().commit();
        session.close();
    }

}

Output: 1

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven

Brak komentarzy:

Prześlij komentarz