views:

48

answers:

1

I have the following mapping in an Ad entity:

class Ad ... {
@Id
    @Column(name = "id", unique = true, nullable = false)   
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_ad_generator")      
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id", nullable = false)
    private Category category;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "city_id", nullable = false)
    private City city;

At some point, I want to persist a new Ad... but i only know the PK id values for category and city (because the entities are converted to DTO's, send to the front end where the id's are stored, then a DTO is sent to the backend with the category and city id's and other data to construct the Ad)

To persist the new ad i do: (em=EntityManager)

City city = em.find(City.class, city_id);
Category category = em.find(Category.class, category_id);

Ad ad = new Ad();
ad.setCity(city);
ad.setCategory(category);
ad.set(...otherstuff);
em.persist(ad);

that's fine and all, but hibernate performs a select for city and a select for category, then performs the insert. If I was doing this in SQL and I knew the id's I would just do an insert statement (no selects before hand)

So, is this wrong the way I am doing it? Or is this just the nature of ORM

+5  A: 

Use getReference instead of find

Maurice Perry
thank you sir..
Billworth Vandory