Mapping OO domain model to database model

Figure 877. Class StudyCourse Slide presentation Create comment in forum
public class StudyCourse {

  private String shortName, fullName;

  public StudyCourse(String shortName, String fullName) {
    this.shortName = shortName;
    this.fullName = fullName;
  @Override public String toString() {
    return fullName + "(" + shortName + ")";

Figure 878. Transient instance Slide presentation Create comment in forum
final StudyCourse csm = new StudyCourse("CSM", "Computer Science and Media");


Computer Science and Media(CSM)

Figure 879. Persistence: Business rules Slide presentation Create comment in forum
  • Both shortName and fullName must be unique and not null.

  • shortName will become the primary key.

  • shortName is to be represented by 3 characters max e.g. CSM.

Figure 880. StudyCourse entity definition Slide presentation Create comment in forum
public class StudyCourse {
  @Column (length = 3 )
  private String shortName;

  @Column(length = 150 ,
     unique=true ,
     nullable=false )
  private String fullName;

CREATE TABLE  StudyCourse(

  PRIMARY KEY  (shortName),
  shortName varchar(3)  NOT NULL,

  UNIQUE KEY (fullName),
  fullName varchar(150) NOT NULL 

The @Entity annotation marks class StudyCourse to become a JPA mapped entity.

Every @Entity must have exactly one @Id property (or a combination of properties) designated to become the entities primary key.

@Column annotations are optional supplying additional JPA mapping meta data

Limit the shortName and fullName attributes' database length.

Property fullName is about to become a unique key.

Since fullName is no primary but just a unique key we have to state the desired business rule constraint explicitly.

exercise No. 40

Database server limitations Create comment in forum


Repeat Figure 880, “StudyCourse entity definition ” but omit the length = 150 constraint.

Analyze the generated schema. What do you observe? Give an explanation.


Read the Mysql server Maximums and Minimums documentation.


The generated schema lacks a unique key definition in contrast to the unique=true setting.

Mysql imposes upper limits on unique key lengths. Omitting length = 150 implies type VARCHAR(255). Depending on the database server's encoding the resulting length exceeds a key's maximum possible length.

Unfortunately this happens silently without even a warning.