简体   繁体   中英

How to map foreign key relations in hibernate

I have customer class and Address class as below: officeAddressId,homeAddressId, and secondaryAddressId in Customer class are for foreign key mapping in tables.

  public class customer implements serializable
    {
    private static final long serialVersionUID= -5830229553758180137L;
    int age;
    String officeAddressId= null;
    String homeAddressId= null;
    String secondaryAddressId= null;
    }

public class Address implements serializable
{
        private static final long serialVersionUID= -5130229553758180137L;
        private String              addressId           = null;
    private String              addressLine         = null;
    private String              cityName            = null;
    private String              stateName           = null;
    private String              countryName         = null;
    private String              pincode             = null;
}

My database table is straight forward:

CREATE TABLE customer
(
customerID varchar(40) primary key,
officeAddressId varchar(40),
homeAddressId varchar(40),
secondaryAddressId varchar(40),
age int 
);

CREATE TABLE Address
(
addressID varchar(40) primary key,
addressLine varchar(40),
cityName varchar(40),
stateName varchar(40),
countryName varchar(40),
pincode varchar(10),
);

I make address objects (3 objects for address one for home,office and secondarycontact) and customer object at service layer and open transaction. I am not sure how should I give the foreign key relation in hbm mapping files and how do I save these four objects(3 address objects and 1 customer object) and in which order that the foreign key relations are persisted in database correctly.

Thanks in advance....

First, change name of your customer class to Customer. Then:

public Class Customer implements Serializable {
    ...

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "office_address_id")
    private Address officeAddress;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "home_address_id")
    private Address homeAddress;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "secondary_address_id")
    private Address secondaryAddress;

    ...
}

and

public Class Address implements Serializable {
    ...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "officeAddress")
    private Set<Customer> officeCustomers = new HashSet<Customer>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "homeAddress")
    private Set<Customer> homeCustomers = new HashSet<Customer>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "secondaryAddress")
    private Set<Customer> secondaryCustomers = new HashSet<Customer>(0);

    ...
}

and of course you can create getter for all customers in Address class.

Here's an answer better tailored to your question.

Assuming your *AddressId columns in the customer table can be foreign keys, then you should map the relationship as a many-to-one in your Customer Hibernate mapping/class. (Note that Java classes should begin with capital letter.)

In Customer class:

//each of these with getters/setters
Address officeAddress;
Address homeAddress;
Address secondaryAddress;

In Customer.hbm.xml file:

<many-to-one name="officeAddress" class="[package.name.]Address" column="officeAddressId"/>
<many-to-one name="homeAddress" class="[package.name.]Address" column="homeAddressId"/>
<many-to-one name="secondaryAddress" class="[package.name.]Address" column="secondaryAddressId"/>

Then, the explicit way to create/save these objects (perhaps in a DAO method) is to get access to a Hibernate Session (via SessionFactory ), create/save the Address objects, set those on the Customer object, and then save it. Something like this:

//in DAO create logic
Session session = sessionFactory.getCurrentSession(); //or openSession()
Address office = new Address();
Address home = new Address();
Address secondary = new Address();
//populate Address objects...
session.saveOrUpdate(office);
session.saveOrUpdate(home);
session.saveOrUpdate(secondary);
Customer customer = new Customer();
//populate Customer object...
customer.setOfficeAddress(office);
customer.setHomeAddress(home);
customer.setSecondaryAddress(secondary);
session.saveOrUpdate(customer);

If you need to update which Address entities a Customer references, then get the objects, set the correct Address objects again, and save the Customer :

//in DAO update logic
Session session = sessionFactory.getCurrentSession(); //or openSession()
Customer customer = (Customer) session.get(Customer.class, customerId);
Address address = (Address) session.get(Address.class, addressId);
customer.setOfficeAddress(address);
session.saveOrUpdate(customer); //updates officeAddressId column to value of addressId

Pretty verbose, but explicit and straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM