@Column: names, lengths, nullability and uniqueness
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The customers table has rules: a name that cannot be empty, a unique e-mail and an optional phone. The entity must describe each column correctly, or a bug hides until the first bad insert.
@Column attributes and when each one matters
@Column describes the database column behind one entity field: its name and facts such as its length or whether it may be NULL. Only name changes the SQL at run time; the other facts are mainly for schema generation.
@Column(name = "full_name", nullable = false, length = 100, unique = true) gives the column name plus three facts about it. Example 1 maps the whole Customer.
Example 1 · src/main/java/com/shoplite/customer/Customer.java and the DDL it describes
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
package com.shoplite.customer;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;import jakarta.persistence.Transient;
import java.time.LocalDateTime;
@Entity@Table(name = "customers")public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "customer_id") private Integer id;
@Column(name = "full_name", nullable = false, length = 100) private String fullName;
@Column(nullable = false, length = 255, unique = true) private String email;
@Column(length = 15) // nullable: phone is optional private String phone;
@Column(name = "created_at", insertable = false, updatable = false) private LocalDateTime createdAt; // MySQL fills it (DEFAULT CURRENT_TIMESTAMP)
@Transient private boolean welcomeMailSent; // in memory only, never stored
protected Customer() { }
public Customer(String fullName, String email, String phone) { this.fullName = fullName; this.email = email; this.phone = phone; }
public Integer getId() { return id; } public String getFullName() { return fullName; } public String getEmail() { return email; } public String getPhone() { return phone; } public LocalDateTime getCreatedAt() { return createdAt; } public boolean isWelcomeMailSent() { return welcomeMailSent; } public void markWelcomeMailSent() { this.welcomeMailSent = true; }}create table customers (customer_id integer not null auto_increment, created_at datetime(6), phone varchar(15), full_name varchar(100) not null, email varchar(255) not null, primary key (customer_id)) engine=InnoDB; alter table customers add constraint UKrfbvkrffamfql7cjmen8v976v unique (email);
What this code does
- The script shows where each attribute goes:
length = 100becamevarchar(100),nullable = falsebecamenot null,unique = truebecame a unique constraint with a generated name. - It is not ShopLite's real table:
created_atcame out asdatetime(6)without a default, and the constraint name is random. That is why ShopLite keeps the hand-written Section 12 schema and only validates against it. welcomeMailSentis@Transient, so it has no column at all.
Example 2 · Validate does not check lengths or NULL rules
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// Wrong on purpose: the table has full_name VARCHAR(100) NOT NULL and phone VARCHAR(15)@Column(name = "full_name", nullable = true, length = 40)private String fullName;
@Column(length = 10)private String phone;INFO ... com.shoplite.ShopliteLabApplication : Started ShopliteLabApplication in 13.698 seconds (process running for 15.253) DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? Loaded: Meena Iyer, phone null, since 2026-06-02T09:05
What this code does
- Both attributes disagree with the real table, yet the app starts and works: validate compared only column names and types (
varcharwithString). - Wrong attributes do no harm at runtime here, but they mislead the next reader and produce a wrong table if anyone generates the schema from the entities. Copy the real values from the
CREATE TABLE.
precision and scale describe a DECIMAL: precision = 10, scale = 2 is DECIMAL(10,2), ten digits with two after the point. Only name (and insertable/updatable, below) changes the SQL your app sends. The rest is used for schema generation, when Hibernate writes CREATE TABLE itself (ddl-auto: create, or a generated script as in Example 1). ShopLite uses ddl-auto: validate, which checks only that each table and column exists and has a compatible type (Example 2), so these attributes are documentation that must match the real table.
What each attribute does:
name: always used. Needed when the column name is not the snake case of the field.nullable,length,unique,precision,scale: generated DDL only; validate does not check them, and MySQL's own constraints do the enforcing.insertable = false,updatable = false: leave the column out ofINSERTorUPDATE.
nullable = false is not input validation
DataIntegrityViolationException is the Spring exception thrown when the database refuses a row, such as a NULL in a NOT NULL column or a duplicate value in a unique column.
Input validation checks what a client sent before any business code runs and answers 400 with every broken field. @Column(nullable = false) is not that. The snippet shows the request DTO that validates, then the entity column.
public record CreateCustomerRequest( @NotBlank @Size(min = 2, max = 100) String fullName, @NotBlank @Email @Size(max = 255) String email, @Pattern(regexp = "^[6-9][0-9]{9}$") String phone) { }
@Column(name = "full_name", nullable = false, length = 100)private String fullName;Example 3 · NULL and duplicate values: MySQL is the one that says no
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
package com.shoplite.customer;
import org.springframework.boot.CommandLineRunner;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.stereotype.Component;
@Componentclass CustomerDemoRunner implements CommandLineRunner {
private final CustomerRepository customers;
CustomerDemoRunner(CustomerRepository customers) { this.customers = customers; }
@Override public void run(String... args) { try { customers.save(new Customer("Asha R", "asha.rao@example.com", null)); } catch (DataIntegrityViolationException e) { System.out.println("Duplicate: " + e.getClass().getSimpleName()); System.out.println(" cause: " + e.getMostSpecificCause().getMessage()); } try { customers.save(new Customer(null, "no.name@example.com", null)); } catch (DataIntegrityViolationException e) { System.out.println("Null name: " + e.getClass().getSimpleName()); System.out.println(" cause: " + e.getMostSpecificCause().getMessage()); } System.out.println("Customers now: " + customers.count()); }}DEBUG ... org.hibernate.SQL : insert into customers (email,full_name,phone) values (?,?,?) WARN ... org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1062, SQLState: 23000 WARN ... org.hibernate.orm.jdbc.error : Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' Duplicate: DataIntegrityViolationException cause: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' DEBUG ... org.hibernate.SQL : insert into customers (email,full_name,phone) values (?,?,?) WARN ... org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1048, SQLState: 23000 WARN ... org.hibernate.orm.jdbc.error : Column 'full_name' cannot be null Null name: DataIntegrityViolationException cause: Column 'full_name' cannot be null DEBUG ... org.hibernate.SQL : select count(*) from customers c1_0 Customers now: 8 The same run with hibernate.check_nullability=true, second part: Null name: DataIntegrityViolationException cause: not-null property references a null or transient value for entity com.shoplite.customer.Customer.fullName
What this code does
- Both
INSERTstatements reached MySQL. Error 1062 is the unique constraintuq_customers_email; error 1048 is theNOT NULLonfull_name. Spring wraps both in its ownDataIntegrityViolationException. - With
check_nullability=true, Hibernate stops the second save itself and noINSERTis sent; the message names the field instead of the column. - Neither message is something to show a user. Bean Validation on the request DTO catches the null name first; the service checks for a duplicate e-mail and still maps the database error to 409 for the rare race.
With the validation starter on the classpath, Hibernate does not even check nullable = false by default. A null name goes into the INSERT, and MySQL refuses it with Column 'full_name' cannot be null (Example 3). The caller gets a DataIntegrityViolationException, not a friendly list of field errors.
ShopLite keeps three layers, each with its own job: the DTO (Bean Validation, Section 15) rejects bad input with clear messages, the entity documents the column, and the database constraint is the last guard against bugs and races, such as two requests with the same e-mail at the same moment.
spring.jpa.properties.hibernate.check_nullability=true makes Hibernate check nullable = false before the INSERT (Example 3 shows both messages). It is still not input validation: one error, no field list, after the business code ran.Mapping customers: full_name, a unique email and a nullable phone
The customers table has full_name and email as NOT NULL, a unique e-mail and an optional phone. Each field copies its column's facts into @Column.
@Column(name = "full_name", nullable = false, length = 100)private String fullName;
@Column(nullable = false, length = 255, unique = true)private String email;
@Column(length = 15)private String phone;fullName would map to full_name by snake case anyway, but naming it keeps the entity readable next to the SQL. phone has no nullable = false because a customer may skip it, and it is a String: phone numbers are text, not numbers to add up.
unique = true on email does not stop duplicates by itself. The MySQL constraint uq_customers_email does, and its error names it: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' (Example 3). The service maps that to the contract's 409 already-exists.
Find the bug
Find the wrong @Column
The table is customers. Tap the line that does not match its column.
Column: email VARCHAR(255) NOT NULL, with a unique constraint.
@Transient fields and columns the database fills
@Transient marks a field that is not stored at all: Hibernate leaves it out of every SELECT, INSERT and UPDATE. Use it for values that live only in memory.
@Transient keeps a field out of the database, and insertable = false, updatable = false keeps a column out of INSERT and UPDATE. Example 4 uses both.
Example 4 · CustomerRepository and a runner: phone, @Transient and created_at
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/customer/CustomerRepository.javapackage com.shoplite.customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Integer> {}
// src/main/java/com/shoplite/customer/CustomerDemoRunner.javapackage com.shoplite.customer;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass CustomerDemoRunner implements CommandLineRunner {
private final CustomerRepository customers;
CustomerDemoRunner(CustomerRepository customers) { this.customers = customers; }
@Override public void run(String... args) { Customer meena = customers.findById(3).orElseThrow(); System.out.println("Loaded: " + meena.getFullName() + ", phone " + meena.getPhone() + ", since " + meena.getCreatedAt());
Customer sneha = new Customer("Sneha Patil", "sneha.patil@example.com", "9876543209"); sneha.markWelcomeMailSent(); customers.save(sneha); System.out.println("Saved id " + sneha.getId() + ", createdAt in memory: " + sneha.getCreatedAt());
Customer reloaded = customers.findById(sneha.getId()).orElseThrow(); System.out.println("Reloaded createdAt: " + (reloaded.getCreatedAt() != null) + ", welcomeMailSent: " + reloaded.isWelcomeMailSent()); }}DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? Loaded: Meena Iyer, phone null, since 2026-06-02T09:05 DEBUG ... org.hibernate.SQL : insert into customers (email,full_name,phone) values (?,?,?) Saved id 9, createdAt in memory: null DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? Reloaded createdAt: true, welcomeMailSent: false
What this code does
- Meena has no phone, so
getPhone()isnull, and theDATETIMEcreated_atarrived as aLocalDateTime. - The
INSERTlists onlyemail, full_name, phone:created_atisinsertable = falseandwelcomeMailSentis@Transient. MySQL filledcreated_at, but the saved object still holdsnull. - The second
findByIdruns a newSELECTand sees the database value (printed astruebecause the time differs on every run).welcomeMailSentis back tofalse: it was never stored.
Use @Transient for values such as welcomeMailSent. Do not confuse it with Java's transient keyword, which is about serialization. A column with insertable = false, updatable = false is still read by SELECT; that fits created_at, which MySQL fills with DEFAULT CURRENT_TIMESTAMP and nobody should change.
The catch: Hibernate does not read the row back after the INSERT, so createdAt stays null on the object you saved, and only a fresh load sees the value MySQL wrote. The Auditing lesson replaces this with timestamps the app sets, so the value is known at once.
Schema-validation errors: missing column and wrong column type
Schema validation is what ddl-auto: validate does at startup: Hibernate reads each table's metadata from MySQL and compares names and types with your entities. Any mismatch stops the app with one exact message.
Two messages cover most mapping slips: a missing column and a wrong column type. Example 5 shows both.
Example 5 · Two schema-validation errors
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// Customer: the field was renamed from phone to mobile, no @Column(name = "phone")@Column(length = 10)private String mobile;
// Product: price as double instead of BigDecimalprivate double price;
// Product: Long id for the INT column product_idprivate Long id;Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing column [mobile] in table [customers] Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)] Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [product_id] in table [products]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]
What this code does
- Each run stopped at startup, before any request. The message names the table and the column, so you know exactly which field to look at.
- Missing column: map the field back with
@Column(name = "phone"), or rename it. Wrong type:foundis the database,expectingis your Java type. UseBigDecimalforDECIMALandIntegerforINT. - Validation stops at the first problem it finds. After a fix, run again: there may be a second one.
Schema validation: missing column [mobile] in table [customers] means a field maps to a column that does not exist: a typo, a renamed field, or a missing @Column(name = ...). Fix the field name or the name attribute, and change the table only when the schema really needs a new column (Flyway, later in this section).
wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)] means the Java type does not fit the SQL type. The found part is the table, the expecting part is what your field asks for. Change the Java type (BigDecimal), not the table.
Fix the error
Fix the mapping from the message
Read the error, then pick the line that replaces the marked line.
Round 1 of 2
The app stops at startup. Fix line 2.
Error
wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]
Next step
Check your understanding
12 quick questions