1

I have two simple entities with one-to-one mapping:

@Entity
@Table(name="DRIVER")
public class Driver implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private long id;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="CAR_ID",referencedColumnName="ID")
private Car car;
}

and:

@Entity
@Table(name="CAR")
public class Car {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private Long id;

@OneToOne(mappedBy="car")
private Driver driver;

@Column(name="MILEAGE")
private Long mileage;
}

To update the mileage I call:

    Car c = em.find(Car.class, id);
    c.setMileage(mileage);

And Hibernate query looks like this:

select
    car0_.ID as ID0_1_,
    car0_.DATE_OF_PURCHASE as DATE2_0_1_,
    car0_.MILEAGE as MILEAGE0_1_,
    car0_.MODEL as MODEL0_1_,
    car0_.PRODUCER as PRODUCER0_1_,
    driver1_.ID as ID1_0_,
    driver1_.CAR_ID as CAR3_1_0_,
    driver1_.NAME as NAME1_0_ 
from
    CAR car0_ 
left outer join
    DRIVER driver1_ 
        on car0_.ID=driver1_.CAR_ID 
where
    car0_.ID=?

What I want is to query Car table only and remove the join operation. I tried to put FetchType.LAZY on both sides, it changes the query a bit but it doesn't remove the join.

Is it possible to do it in such model?

It looks like whenever you query for the owning entity, the owned entity is queried as well but I'm not sure if this is a rule.

jarosik
  • 4,136
  • 10
  • 36
  • 53
  • 4
    possible duplicate of [Making a OneToOne-relation lazy](http://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy) – Glorfindel Jul 24 '15 at 09:56
  • Alright, I changed my code according to the best answer from the post you pointed. Now Hibernate wont make a join but still makes two selects. Can I avoid the second select somehow? – jarosik Jul 24 '15 at 10:27
  • Do you at least understand the reason why Hibernate does it? It is nicely explained in the linked question. – Dragan Bozanovic Jul 24 '15 at 12:05

0 Answers0