Suppose, you have to store orders in a SQL DBMS. An order consists of header (address, date, number etc.) as well as a variable count oflines (amount, product, price, tax, …). This should be stored in two tables.

Table Order (
        orId Integer,
        [...]
)    

Table OrderLine (
        olId Integer,
        olOrderId Integer,
        [...]
)  

To prevent working directy with SQL, you use JPA. Two entity classes, which are annoted.

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

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "orId")
    private Integer _id;
    [...]
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "olOrderId", referencedColumnName="olId")
    private List<OrderFeature> _features;

@Entity
@Table(name = "OrderLine")
public class OrderLine implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "olId")
    private Integer _id;
    [...]

An order hast to know it's lines. There is no need for a line to know it's order. In Order we store the lines within a list. A line dosn't have a link to an order. This is a unidirectional OneToMany connection. Within the DBMS this is the other was round: Every line consists a foreign key, pointing to an order. So far, it seems to be easy and you may have read that in divers books about JPA2 or JEE6. And if you let the system create the tables, everything works fine.

The column names will show you: In this case we use a legacy database. Our admin created a special naming schema (ok, in this example I did it by myself). And storing doesn't work. But why?

An order line may not exist without order. Thus, olOrderId always has to link to an orId. And like the admin always does, this column is defined to be NOT NULL. JPA stores the line with two accesses: First, the order is stored with every line. Next the system retrieves the new generated order id and then updates the lines. Since the id is not known whilst inserting the lines, this field keeps empty, so NULL.

Solution: Persuade the admin to allow this column to be NULL.