Owning side, mappedBy and join columns
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A new watch is added to the Smart Watches category in Java, yet MySQL rejects the row with "category_id cannot be null". Two Java fields describe one column, and only one of them counts.
The owning side holds the foreign key
The owning side of a relationship is the field whose entity table holds the foreign key column. Hibernate writes the column only from this side. The other side, marked with mappedBy, is the inverse side, a read-only mirror.
ShopLite saves a new product into a category. Hibernate must decide which of the two fields writes products.category_id.
// Owning side: Product (table products has category_id)@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "category_id")private Category category;
// Inverse side: Category (mappedBy = the owning field's name)@OneToMany(mappedBy = "category")private List<Product> products = new ArrayList<>();Example 1 · WatchLaunchService.java: setting the owning side
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.category.Category;import com.shoplite.lab.category.CategoryRepository;import com.shoplite.lab.product.Product;import com.shoplite.lab.product.ProductRepository;
@Serviceclass WatchLaunchService {
private final CategoryRepository categories; private final ProductRepository products;
WatchLaunchService(CategoryRepository categories, ProductRepository products) { this.categories = categories; this.products = products; }
/** The bug: only the mappedBy side is changed. */ @Transactional public void addToListOnly() { Category watches = categories.save(new Category("Smart Watches", categories.getReferenceById(1))); Product watch = new Product("ACC-SW01", "Noise ColorFit Pro 5", new BigDecimal("3499.00"), 25); watches.getProducts().add(watch); products.save(watch); }
/** The fix: set the owning side, the field that holds the foreign key. */ @Transactional public void setOwningSide() { Category watches = categories.save(new Category("Smart Watches", categories.getReferenceById(1))); Product watch = new Product("ACC-SW01", "Noise ColorFit Pro 5", new BigDecimal("3499.00"), 25); watch.setCategory(watches); // owning side: this writes category_id products.save(watch); System.out.println("Saved product " + watch.getId() + " in category " + watches.getId()); System.out.println("watches.getProducts().size() = " + watches.getProducts().size()); }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.stereotype.Component;
@Component@Profile("owning-side")class OwningSideDemo implements CommandLineRunner {
private final WatchLaunchService service;
OwningSideDemo(WatchLaunchService service) { this.service = service; }
@Override public void run(String... args) { if (java.util.List.of(args).contains("bug")) { try { service.addToListOnly(); } catch (DataIntegrityViolationException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMostSpecificCause().getMessage()); } } else { service.setOwningSide(); } }}
// Product in this lab has a constructor without a category, plus:// public void setCategory(Category category) { this.category = category; }DEBUG SQL - insert into categories (name,parent_id) values (?,?) TRACE bind - binding parameter (1:VARCHAR) <- [Smart Watches] TRACE bind - binding parameter (2:INTEGER) <- [1] DEBUG SQL - insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) TRACE bind - binding parameter (1:BOOLEAN) <- [true] TRACE bind - binding parameter (2:INTEGER) <- [8] TRACE bind - binding parameter (3:VARCHAR) <- [Noise ColorFit Pro 5] TRACE bind - binding parameter (4:NUMERIC) <- [3499.00] TRACE bind - binding parameter (5:VARCHAR) <- [ACC-SW01] TRACE bind - binding parameter (6:INTEGER) <- [25] Saved product 16 in category 8 watches.getProducts().size() = 0
What this code does
watch.setCategory(watches)sets the owning field, so parameter 2 of the products insert is the new category id (8).categories.getReferenceById(1)gives a proxy for Electronics without a SELECT; only its id is needed forparent_id.watches.getProducts().size()is still 0: the row is in MySQL, but the Java list was never changed. The next lesson fixes that with helper methods.
A bidirectional link is two Java fields describing one column. If they disagree, Hibernate must pick one, and JPA fixes the choice: the owning side wins, the inverse side is ignored when writing.
A quick test: the side without mappedBy is the owner. In a @ManyToOne / @OneToMany pair, the @ManyToOne is always the owner, so mappedBy can only go on the @OneToMany. The lab runs in this lesson also log bound values (org.hibernate.orm.jdbc.bind: TRACE), so you can see what goes into each ?.
The bug: adding to the mappedBy list only
The inverse side is the field with mappedBy, such as Category.products. Changing only this list does not change the database: Hibernate ignores it when saving, so category_id is written as NULL.
A new watch is added with getProducts().add(watch) and nothing else. The Java reads correctly, so watch the value bound to category_id.
Example 2 · addToListOnly(): the foreign key is never written
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
/** The bug: only the mappedBy side is changed. */@Transactionalpublic void addToListOnly() { Category watches = categories.save(new Category("Smart Watches", categories.getReferenceById(1))); Product watch = new Product("ACC-SW01", "Noise ColorFit Pro 5", new BigDecimal("3499.00"), 25); watches.getProducts().add(watch); // inverse side: Hibernate ignores it products.save(watch);}
// run with the argument "bug": OwningSideDemo catches the exception and prints itDEBUG SQL - insert into categories (name,parent_id) values (?,?) TRACE bind - binding parameter (1:VARCHAR) <- [Smart Watches] TRACE bind - binding parameter (2:INTEGER) <- [1] DEBUG SQL - insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) TRACE bind - binding parameter (1:BOOLEAN) <- [true] TRACE bind - binding parameter (2:INTEGER) <- [null] TRACE bind - binding parameter (3:VARCHAR) <- [Noise ColorFit Pro 5] TRACE bind - binding parameter (4:NUMERIC) <- [3499.00] TRACE bind - binding parameter (5:VARCHAR) <- [ACC-SW01] TRACE bind - binding parameter (6:INTEGER) <- [25] WARN error - HHH000247: ErrorCode: 1048, SQLState: 23000 WARN error - Column 'category_id' cannot be null DataIntegrityViolationException: Column 'category_id' cannot be null
What this code does
- The product is in the category's list, yet parameter 2 (
category_id) is bound to[null]: Hibernate read onlywatch.category, which was never set. - MySQL rejects the row (error 1048), Spring turns it into
DataIntegrityViolationException, and the whole transaction rolls back, so "Smart Watches" is not saved either. - Changing the list was not wrong; changing only the list was.
In ShopLite the column is NOT NULL, so MySQL refuses the row with "Column 'category_id' cannot be null" and nothing is saved. If the column allowed NULL it would be worse: the insert succeeds, the product belongs to no category, and the bug shows up days later as a phone missing from the Mobiles page.
The fix is one line: set the owning side with watch.setCategory(watches). Change the list as well to keep the Java objects in step; the next lesson wraps both changes in one helper method.
Find the bug
Find the line that is not saved
Tap the line that never reaches the database.
Save a new watch in the Smart Watches category.
Round 1 of 3@JoinColumn name and nullable; unidirectional @OneToMany
A unidirectional relationship is mapped from one side only. A unidirectional @OneToMany is a parent list with no field on the child, so JPA assumes a join table, or needs @JoinColumn and extra UPDATE statements.
Two mapping details change what Hibernate sends: whether the link is required, and whether the child has a field that points back.
Example 3 · @JoinColumn(nullable = false): Hibernate stops before the SQL
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/product/Product.java (variant)@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "category_id", nullable = false)private Category category;
// same addToListOnly() as Example 2DEBUG SQL - insert into categories (name,parent_id) values (?,?) TRACE bind - binding parameter (1:VARCHAR) <- [Smart Watches] TRACE bind - binding parameter (2:INTEGER) <- [1] DataIntegrityViolationException: not-null property references a null or transient value for entity com.shoplite.lab.product.Product.category
What this code does
- No
insert into productsappears: Hibernate checked the required field first and refused to send it. - The message names the exact field,
Product.category, which makes the bug quicker to find than MySQL's column error. nullable = falseis a mapping fact for Hibernate and schema checks; it does not replace Bean Validation on request DTOs.
Example 4 · Unidirectional @OneToMany: a join table, a failed insert, an extra UPDATE
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// Run 1 and 2: products list on Category, Product has no category field@OneToManyprivate List<Product> products = new ArrayList<>();
@Override@Transactionalpublic void run(String... args) { Category watches = categories.save(new Category("Smart Watches")); Product watch = products.save( new Product("ACC-SW01", "Noise ColorFit Pro 5", new BigDecimal("3499.00"), 25)); watches.getProducts().add(watch); System.out.println("Added " + watch.getName() + " to " + watches.getName());}
// Run 2 adds @JoinColumn(name = "category_id") under @OneToMany
// Run 3: the same idea on the nullable parent_id column@OneToMany@JoinColumn(name = "parent_id")private List<Category> children = new ArrayList<>();
@Override@Transactionalpublic void run(String... args) { Category electronics = categories.findById(1).orElseThrow(); Category wearables = categories.save(new Category("Wearables")); electronics.getChildren().add(wearables); System.out.println("Added " + wearables.getName() + " under " + electronics.getName());}--- Run 1: no mappedBy, no @JoinColumn (startup) ERROR LocalContainerEntityManagerFactoryBean - Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory [persistence unit: default] ; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [categories_products] ... Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [categories_products] --- Run 2: @JoinColumn(name = "category_id") DEBUG SQL - insert into categories (name) values (?) DEBUG SQL - insert into products (is_active,name,price,sku,stock) values (?,?,?,?,?) WARN error - HHH000247: ErrorCode: 1364, SQLState: HY000 WARN error - Field 'category_id' doesn't have a default value --- Run 3: children with @JoinColumn(name = "parent_id") DEBUG SQL - select c1_0.category_id,c1_0.name from categories c1_0 where c1_0.category_id=? DEBUG SQL - insert into categories (name) values (?) DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? Added Wearables under Electronics DEBUG SQL - update categories set parent_id=? where category_id=?
What this code does
- Run 1: without
mappedBy, JPA expects a join table namedcategories_products;ddl-auto=validatefinds no such table and the app does not start. - Run 2: the column is right, but the insert leaves
category_idout, planning to set it later with an UPDATE. MySQL refuses a NOT NULL column with no default. - Run 3 shows the plan on a nullable column: insert without
parent_id, load Electronics' children, thenupdate categories set parent_id=?. A bidirectional mapping does it in one insert.
@JoinColumn(name = "category_id", nullable = false) tells Hibernate the link is required. It then checks the field before sending any SQL and fails with "not-null property references a null or transient value", a clearer message than MySQL's. Add optional = false on @ManyToOne to say the same thing to JPA.
Without mappedBy and without @JoinColumn, a unidirectional @OneToMany makes JPA assume a separate join table (categories_products); ShopLite has no such table, so ddl-auto=validate stops the app at startup. With @JoinColumn on the list the column is right, but Hibernate inserts the child without the foreign key and sends an extra UPDATE afterwards, and on a NOT NULL column such as products.category_id the first insert already fails. Map the @ManyToOne on the child instead, and add the list with mappedBy only if you need it.
Errors: an unknown mappedBy property and a NULL foreign key
mappedBy is an attribute of @OneToMany that holds the name of the Java field on the other entity that owns the link, such as mappedBy = "category". It takes a field name, never a column name.
A wrong mappedBy name stops the app at startup, and a missing owner gives a NULL foreign key. Both errors name the culprit.
Example 5 · mappedBy with a misspelled field name
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/category/Category.java (variant)@OneToMany(mappedBy = "categry") // typo: Product has no field "categry"@OrderBy("id")private List<Product> products = new ArrayList<>();ERROR LocalContainerEntityManagerFactoryBean - Failed to initialize JPA EntityManagerFactory: Collection 'com.shoplite.lab.category.Category.products' is 'mappedBy' a property named 'categry' which does not exist in the target entity 'com.shoplite.lab.product.Product' ... Caused by: org.hibernate.AnnotationException: Collection 'com.shoplite.lab.category.Category.products' is 'mappedBy' a property named 'categry' which does not exist in the target entity 'com.shoplite.lab.product.Product'
What this code does
- Hibernate checks every
mappedBywhile building the EntityManagerFactory, so the app fails at startup, before any request. - The message gives the collection, the bad property name and the target entity: change
"categry"to"category", the field name inProduct. mappedBy = "category_id"fails the same way: it wants a Java field name, never a column name.
A typo such as mappedBy = "categry", or a column name such as mappedBy = "category_id", stops the app at startup. Hibernate 7 says "Collection '...Category.products' is 'mappedBy' a property named 'categry' which does not exist in the target entity '...Product'"; older versions said "mappedBy reference an unknown target entity property". The fix is the same: use the exact field name.
"Column 'category_id' cannot be null" (MySQL error 1048) at save time means the owning field was null when the insert ran: look for code that changed only the list, or a constructor that never set the link. A third message, "Field 'category_id' doesn't have a default value" (error 1364), means Hibernate left the column out of the insert, which is the unidirectional @JoinColumn case above. Read the message before changing any code.
Next step
Check your understanding
12 quick questions