TheCurious
TheCurious

Reputation: 613

Hbernate : unideirection @onetoone with cascade enable

I have a unidirection one to one mapping between Flight(Parent) and Airline(Child),Below is my code-

public class Airline {
..
    @OneToOne(cascade=CascadeType.ALL)
    Flight flight;
}

Flight not have any reference of Airline this have id,name their getter and setter.

I am persisting airline and cascade is enable.

    Flight flight= new Flight();
    flight.setName("flight2");

    Airline airline= new Airline();
    airline.setName("Air India");
    airline.setFlight(flight);

    Session session=sessionFactory.openSession();
    session.saveOrUpdate(airline);
    session.saveOrUpdate(flight);

This throws me exception MySQLSyntaxErrorException: Unknown column 'flights_id' in 'field list'. so I added @JoinColumn This worked thanks of answers.

EDIT----

But I made a bidirectional without mappedby(ie two unidirectional associations) and didnot applied @joinColumn in second table ie

public class Airline {
        @JoinColumn("flight_ref_id")
        @OneToOne(cascade=CascadeType.ALL)
        Flight flight;
    }


public class Flight {
        @OneToOne(cascade=CascadeType.ALL)
        Airline airline;
    }

And

    airline.setFlight(flight);
    flight.setAirLine(airline)
    Session session=sessionFactory.openSession();
    session.saveOrUpdate(airline);

Now there is no exception,even no @joincolumn in Flight.it created column airline_id why?

mysql> select * from Airline;
+----+-----------+---------------+
| id | name      | flight_ref_id |
+----+-----------+---------------+
|  1 | Air India |          NULL |
+----+-----------+---------------+
1 row in set (0.00 sec)

mysql> select * from Flight;
+----+--------+------------+
| id | name   | airline_id |
+----+--------+------------+
|  1 | Del-NJ |          1 |
+----+--------+------------+

And in db flight_ref_id is null.why?

Upvotes: 2

Views: 265

Answers (2)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

You are not specifying the join column name for your db table. Assuming the airline table has a join column named flight_id, you should use @JoinColumn to specify the name -

public class Airline {

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "flight_id")
    Flight flight;
}

EDIT

You need to specify mappedBy in one side of the relation, like below -

public class Flight {
    @OneToOne(mappedBy = "flight")
    Airline airline;
}

where flight is the name of the property in the Airline entity. This will prevent hibernate to generate foreign key columns on both sides of the relation.

Upvotes: 2

Angga
Angga

Reputation: 2323

you need to add @JoinColumn annotation to add one more column that serve as flight foreign key

public class Airline {
..
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "flights_id", nullable = false)
    Flight flight;
}

Upvotes: 2

Related Questions