SSG
SSG

Reputation: 314

Hibernate Save Entity

I have 2 Entities, Vehicle & Driver. A Vehicle has a Driver. In the Vehicle class generated by Hibernate, this notation is represented by...

public class Vehicle
{
    private Driver driver;
    ...
    ...
    ...
}

In DB the following is the scenario...

table vehicle
    id INT
    name VARCHAR(20)
    driverId INT

table driver
    id INT
    name VARCHAR(45)

I am creating a Vehicle and want to assign a existing Driver. Using Hibernate, when I create a Vehicle object and save it, I have to do the following...

// Load Driver
Driver driver = (Driver) session.load(Driver.class, Integer.parseInt(iKnowTheDriverId));

// Create Vehicle
Vehicle v = new Vehicle();
v.setDriver(driver);

Do I need to load the corresponding Driver entity everytime or is there anyway to just set the Driver ID?

Thanks in advance...

SG

Upvotes: 0

Views: 2745

Answers (3)

Aniket
Aniket

Reputation: 11

try {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(userDetails);
        Long userId = userDetails.getId();
        session.getTransaction().commit();
        session.close();
        logger.info("Successfully added the user");
        return userId;
    } catch (Exception e) {
        logger.error("error in saving the user in user table", e);
    }

Upvotes: 0

dcernahoschi
dcernahoschi

Reputation: 15240

You need to get a reference to the corresponding Driver when saving a new Vehicle.

// Load Driver
Driver driver = (Driver) session.load(Driver.class, driverId);

// Create Vehicle
Vehicle v = new Vehicle();
v.setDriver(driver);
v.setName("someName");

session.save(vehicle);

But using session.load() to get the corresponding Driver is a good choice to avoid an SQL SELECT to the database. The driver object will not be fully initialized until you read a property on it. Only then the SQL SELECT is issued.

Upvotes: 2

Tobb
Tobb

Reputation: 12205

You can do this:

Driver temp = new Driver();
temp.setId(iKnowTheDriverId);

v.setDriver(temp);

session.merge(v);

It might be some differences between the save-methods, but if you use Session#merge() it should work. It will then merge the detached driver with an existing by checking their id, and null values in the detached object won't overwrite not-null values in the persisted state. Just make sure you have a CascadeType.MERGE/ALL on your reference from Vehicle to Driver.

Upvotes: 0

Related Questions