📈
Development Docs - Java
  • Introduction
  • General
    • Compiling and running
    • Code Style
    • Operators
    • Control Flow
    • Inheritance
    • Enums
    • Manifest
    • Immutable and Unmodifiable
    • Regular Expression
    • Executable class
    • Text Formatting
  • Beans and Objects
    • Primitives
    • Variables
    • Java Beans
    • Serialization
    • Hashcode, equals and toString
  • Generics
    • General
    • Generic Methods
    • Bound Parameters
    • Wildcards
    • Type Erasure
    • Type Parameter Naming Conventions
  • Documentation
    • Comments
    • Javadoc
      • Code Example
  • Collections and Data Structures
    • Arrays
    • Iterable
    • Collection
    • List
    • Set
    • Queue
    • Stack
    • Map
  • Introspection
    • Properties
  • Errors and Exceptions
    • General
    • Catching Exceptions
    • Checked Exceptions
  • Functional
    • General
    • Interfaces
    • Function
    • Predicate
    • Consumer
    • Supplier
    • Method References
    • Lambdas
    • Streams
      • Common Operations
      • Searching for Values
      • Other Operations
      • Data Structure Transformations
  • Internationalization
    • General
    • Locale
    • Resource Bundle
    • Formatting
  • Java Bean Validation
    • Specification
    • Annotations
    • Validator
  • Utilities Classes
    • Libraries
    • Constants Class
    • Preconditions
    • Apache Commons
      • Strings
      • Dates
    • Guava
      • Preconditions
  • JPA
    • General
    • Logging
    • JPA Entities
    • Lifecycle
    • JPQL
    • Criteria API
  • HIBERNATE
    • Logging
      • Sessions
      • Statistics
      • Queries
      • Hibernate Properties
    • More Information
  • Ant
    • Scripts
    • Examples
      • Replace Version
      • Merge Files
      • Execute Command
  • LOGGING
    • SL4J
    • Log4j
      • Logging Levels
      • Formatted Messages
      • Templated Messages
      • Mapped Diagnostic Context
    • Hikari
  • Testing
    • Libraries
    • Junit
      • Setting Up Tests
        • JUnit 4 Tests
        • JUnit 5 Tests
      • Disable Tests
      • Test Lifecycle
      • Testing Exceptions
      • Display Name
      • Test Files
      • Extensions
        • Annotation Extension
    • Mockito
      • Mocking
      • Verify Calls
      • Throw Exceptions
      • Capture Arguments
  • KeyStore
    • Types
    • Generation
    • Certificates
    • Keys
    • Reading
  • Jackson
    • General
    • Deserialize
      • Dates
      • Enums
    • Object Hierarchy
    • Ignoring Data
    • Change Field Name
    • Mixin
  • Maven
    • Execution
      • Commands
      • Parameters
      • Building the Project
    • Deployments
      • Configuration
      • Deploying Web Projects Locally
      • Deploying Documentation
    • Tests
      • Deploying the WAR for Testing
    • Site
      • Setting Up
      • Reports
      • Theme
    • Maven Lifecycle
      • Binding Plugins to Phases
    • Dependency Management
      • Artifact Repositories
    • Maven Archetype
      • Testing Archetypes
    • Configuration
      • Project Setup
      • Maven Build Plugins
      • Profiles
        • Forcing an Active Profile
      • Default Properties
      • Parent POM
      • Settings File
      • Versions
      • Extensions
      • Setting Up the JAR
        • Attach Sources
        • Attach Javadocs
        • Manifest
    • JPA
      • Generating Metamodel
    • Frontend with Maven
      • WebJars
      • npm and Webpack
    • Continuous Integration
    • Ant
    • Executable JAR
  • Spring
    • General
    • SpEL
    • Files
    • Sending Mails
  • Spring Configuration
    • Profiles
    • Conditional Configuration
    • Properties Object
  • Spring Dependence Injection
    • Injections
      • Asking for a Specific Bean
    • Injecting Values
    • Injecting Multiple Instances
    • Interdependence
    • Component Scanning
  • Spring Beans
    • Initialization
    • Destruction
    • Extending Initialization
  • Spring Data
    • Configuration
      • Common Persistence Beans
      • Datasource
      • Persistence Providers
    • Repositories
      • Custom Repositories
      • Queries
      • Sorting and Paging
      • Example API
    • Transactional
      • Configuration
      • Annotation
      • Transaction Aspect
      • Transactional Test
  • Spring MVC
    • General
    • Setting Up a Web Application
    • Serving Resources
    • Securing URLS
    • Controllers
      • Mapping and Choosing Controller Methods
      • Mapping Controller Variables
      • Request Argument Validation
      • Controller Advices
    • Error Handling
    • Binding Configuration
    • Model Attributes
    • View Resolvers
    • Resolving Sort and Pageable Arguments
    • Logging
    • Validating Request Data
  • Spring WS
    • Examples
  • Spring Boot
    • General
    • Setting Up
    • Logging development info
    • Remote Debugging
  • Spring Security
    • Examples
    • Setting Up
      • Method Security
  • Spring AOP
    • More Information
    • Configuration
    • Aspect
    • Logging Aspect Example
  • Spring Cache
    • Configuration
  • Spring Integration
    • Gateway
    • Routing
    • Services
  • Testing Spring
    • Test configuration
    • Setting Up Junit
    • Conditional Tests
    • Initializing DB
    • Spring MVC
      • Setting Up the MVC Test Context
      • Request Path Testing
      • Testing JSON
      • Argument Resolvers
      • Response Status
  • JMeter
    • General
  • Neo4J
    • More Information
    • Cypher
    • Testing
  • JQAssistant
    • More Information
    • Maven Plugin
      • Git
      • Maven Dependencies
    • Queries
      • git
      • Tags
      • File Structure
      • Structure
      • Pruning
      • Maven
      • Controller
      • Detecting Problems
      • Persistence
    • Concepts
    • Constraints
    • Groups
    • Rules
      • Custom Rules
  • AspectJ
    • Wrapping Method
Powered by GitBook
On this page
  • Constraints
  • Additional Constraints
  • Comparison Methods
  • Annotations
  • Ids
  • Defining the Entity Name
  • Transient Fields
  • XML
  • Additional Constraints

Was this helpful?

  1. JPA

JPA Entities

Java beans can be mapped to the database tables.

This can be done with XML or annotations.

Constraints

  • Usage of JPA annotations or XML mapping

  • Non final classes

  • Non final getters and setters

Additional Constraints

These are recommended, but not compulsory:

  • Extend the equals method

  • Extend the hashCode method

  • Extend the toString method

Comparison Methods

For the equals and hashCode methods do not use the id for this, make use of the unique fields.

Annotations

@Entity(name = "SimpleEntity")
@Table(name = "simple_entities")
public class SimpleEntity {

    /**
     * Entity's ID.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, unique = true)
    private Integer           id               = null;

    /**
     * Name of the entity.
     */
    @Column(name = "name", nullable = false, unique = true)
    private String            name             = "";

    public SimpleEntity () {
        super();
    }

    @Override
    public final boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        final SimpleEntity other = (SimpleEntity ) obj;
        return Objects.equals(name, other.name);
    }

    @Override
    public final Integer getId() {
        return id;
    }

    @Override
    public final String getName() {
        return name;
    }

    @Override
    public final int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public final void setId(final Integer identifier) {
        id = checkNotNull(identifier, "Received a null pointer as identifier");
    }

    @Override
    public final void setName(final String value) {
        name = checkNotNull(value, "Received a null pointer as name");
    }

    @Override
    public final String toString() {
        return MoreObjects.toStringHelper(this).add("name", name).toString();
    }

}

Ids

Id columns are annotated with @Id:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, unique = true)
private Integer id = null;

When using composite ids these can be defined into a class id:

@Entity(name = "CompositeKeyIdClassEntity")
@Table(name = "composite_key_idclass_entities")
@IdClass(CompositeKey.class)
public class CompositeKeyIdClassEntity implements Serializable {

    private static final long serialVersionUID = -4338241927428303803L;

    @Id
    @Column(name = "id1", nullable = false, unique = true)
    private Integer           id;

    @Id
    @Column(name = "id2", nullable = false, unique = true)
    private Long              supportId;

   // Constructor, getters, setters, etc...

}

This way they can be handled as a single object.

Defining the Entity Name

By default JPA implementations will take the name of the class as the entity name. In this case the entity will be named SomeEntity.

@Entity
@Table(name = "table")
public class SomeEntity

This can be changed by defining a name in the annotation. This will set the entity name as NamedEntity:

@Entity(name = "NamedEntity")
@Table(name = "table")
public class SomeEntity

Transient Fields

Any field containing data which should not be persisted has to be marked with the @Transient field. It is not recommended using this annotation, and it may be a hint telling that the entity is doing something else apart from storing persistent data.

XML

Additional Constraints

Requirementes may vary between implementations, but there are some recommended thinks to take care of:

  • Avoid final classes

  • Avoid final getters and setters for lazy fields

PreviousLoggingNextLifecycle

Last updated 5 years ago

Was this helpful?