środa, 12 czerwca 2013

Hibernate relation: one to one (bidirectional)

1. Database schema

2. Entity class:

import javax.persistence.*;
import java.sql.Date;

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

    @Id
    @GeneratedValue
    private Long id;

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

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

    @Column(name = "birthDate")
    private Date birthDate;

    @Column (name = "address")
    private  String emailAddress;

    @OneToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "creditCardId")
    private CreditCard creditCard;


    public User() {
    }

//getters and setters

}

import javax.persistence.*;
import java.sql.Date;

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

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String number;

    @Column
    private Date expiredDate;

    @OneToOne(mappedBy = "creditCard")
    private User user;

    public CreditCard() {
    }

    public CreditCard(String number, Date expiredDate) {
        this.number = number;
        this.expiredDate = expiredDate;
    }


}

3. Hibernate configuration file

Put annotated classes User.java and CreditCard.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.User"/>
        <mapping class="net.hibernateApp.packt.maven.domain.CreditCard"/>

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

4. Run

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

import java.sql.Date;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        //WRITE
        User user = new User();
        user.setFirstName("Christopher");
        user.setSurName("Stepniak");
        user.setBirthDate(new Date(System.currentTimeMillis()));
        user.setCreditCard(new CreditCard("cardNumber", new Date(System.currentTimeMillis())));
        saveUser(user);

        CreditCard creditCard = (CreditCard) list("CreditCard").get(0);
        System.out.println(creditCard.getUser().getFirstName());
    }

    private static List list(String sourceTable) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        List objects = session.createQuery("from "+sourceTable).list();
        session.close();
        return objects;
    }

    
    private static User saveUser(User user){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(user);
        user.setId(id);
        session.getTransaction().commit();
        session.close();
        return user;
    }


}

Output:  Christopher

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

Brak komentarzy:

Prześlij komentarz