title: EJB3 Mappings/ onetomany/manytoone how to handle relationships
body: <p>I am working with Java EE JSP/EJB3 and I have a problem implementing relations between tables. Initially I was thinking of storing the id but I've read that it would defeat the purpose of EJBs which store references to objects</p>
  
  <p>As a test example to explain my problem I came up with a Car Model and a Car Brand relation. In this web application The user creates the brands first.  then create the cars and select the brand from a dropdown.</p>
  
  <p>Car  ->rand: many to one
  Brand->Car: one to many</p>
  
  <pre><code>public class Brand implements Serializable {
    private static final long serialVersionUID = 1L;
  
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private long id;
  
    @Column(name="brand_name")
    private String brand_name;
  
    @Column(name="cars_fk")
    private Set&lt;Car&gt; cars;
  ...
  
  }
  </code></pre>
  
  <p>The following is the car Entitybean</p>
  
  <pre><code>public class Car implements Serializable {
    private static final long serialVersionUID = 1L;
  
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private long id;
  
    private Brand brand;
  
    @ManyToOne(fetch = FetchType.LAZY)
    @Column(name="brand_FK")
    private Brand brand;
  ...
  
  }
  </code></pre>
  
  <p>Given that the above is correct (which I'm not sure of)</p>
  
  <p>What is the best practice to handle inputting of these </p>
  
  <p>lets say i have this html ( if the select has to be different please do tell )</p>
  
  <pre><code>&lt;form action="processCar.jsp"&gt;
    Model: &lt;input type="text" name="title"&gt;&lt;br&gt;
  
    &lt;select&gt;
      &lt;option value="volvo"&gt;Volvo&lt;/option&gt;
      &lt;option value="saab"&gt;Saab&lt;/option&gt;
      &lt;option value="mercedes"&gt;Mercedes&lt;/option&gt;
      &lt;option value="audi"&gt;Audi&lt;/option&gt;
    &lt;/select&gt; 
  
    &lt;input type="submit" value="Submit"&gt;
  &lt;/form&gt; 
  </code></pre>
  
  <p>The brand options are loaded from the  Brand.findAll.</p>
  
  <p>Also if this is correct, where does the change over from  brand name/id to an entity object Brand is done ? in the session bean ?</p>
  
  <pre><code>public void createCar(String title,String brandname){
     Query query = em.createNamedQuery("Brand.getBrandbyName");
     query.setParameter("brand_name", brandname);
     Brand brand = (Brand)query.getSingleResult();
     carSLSBManagement.create(title,brand);
  }
  </code></pre>
  
  <p>Thanks in advance</p>