Element collection Vs One to Many in JPA and hibernate

Element collection Vs One to Many in JPA and hibernate

Introduction:

Inside any project will have a database for saving and fetching the data from it, and will save the data inside the Table. you can use a relational database like MySQL and Postgress or you can use a NoSQL database like Mongo DB or Cassandra DB.

By the way, this article will explain JPA inside the spring project for representing relational databases I will focus on one to many annotation and Element collection annotations.

JPA in Spring?boot:

Spring Boot JPA is a Java specification for managing relational data in Java applications. It allows us to access and persist data between Java object/ class and relational database. JPA follows Object-Relation Mapping (ORM). It is a set of interfaces.

for more information about JPA

One to Many annotations:

We need to use One to Many annotations if we create a relation between two entities (TABLE).

Look at the following code:

We can represent Store, the store have many branches, and they both are an entity, that is mean they both have a table inside our database.

Store.java:

@Entity
@Table(name = "store")
public class Store{
@Id    
@GeneratedValue(strategy = GenerationType.IDENTITY)    
private Long id;     
@Column(name = "name")    private String name; 
@Column(name = "ad_video_url")    private String adVideoUrl;
@OneToMany(mappedBy = "store" , cascade = CascadeType.ALL)       
private Set<Branch> branches = new HashSet<>();
}        

And the branch.class

@Entity
public class Branch{
@Id    
@GeneratedValue(strategy = GenerationType.IDENTITY)    
private Long id;
@Column(name = "name")    
private String name;
@Column(name = "ad_video_url")    
private String adVideoUrl;
//if you want you can remove the following annotation
@ManyToOne    
@JsonIgnoreProperties(value = "branches", allowSetters = true)    private AscStore store;
} 
        

After running the code, the hibernate will create two tables inside your database the first one called the store and the second called branch.

And now we need to create a repository for both entities to insert and get the data from the database.

We can use @Repository to create a Repository component.

StoreRepository.java

@Repository
public interface StoreRepository extend JpaRepository<Store,Long>
{
}        

And now we need to create a Repository for the branch entity.

BranchRepository.java

@Repository
public interface BranchRepository extend JpaRepository<Branch,Long>
{
}        

And after that, we have a new relationship between Store and Branch

Elementcollection annotation:

ElementCollection is a standard JPA annotation, which is now preferred over the proprietary Hibernate annotation CollectionOfElements.

It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @embeddable

It also means that the elements are completely owned by the containing entities: they’re modified when the entity is modified, deleted when the entity is deleted, etc. They can’t have their own lifecycle.

Look at the following code to see how we can implement Elementcollection class.

the simplest term, @ElementCollection tells the compiler that we are mapping a collection, in which, @CollectionTable gives the name of the target table, and then @JoinColumn specifies the actual column we join like below:

From the last example, we have now two entities Store and Branch, and the relation between them, and now I will add a new class Product.

product.java class

@Embeddable
@Data
public class product{
// we dont need to use id becouse it is not a entity
@Colume(name="product_name")
private String productName;
@Colume(name="product_prict")
private Double productPrice;
}        

And now we will add a new Elementcollection annotation in the store.java class and add a new product object from Product Class.

@Entity
@Table(name = "store")
public class Store{
@Id    
@GeneratedValue(strategy = GenerationType.IDENTITY)    
private Long id;
@Column(name = "name")    private String name;
@Column(name = "ad_video_url")    private String adVideoUrl;
@OneToMany(mappedBy = "store" , cascade = CascadeType.ALL)       
private Set<Branch> branches = new HashSet<>();
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "store_product", joinColumns = @JoinColumn(name = "store_id", nullable = false), uniqueConstraints = @UniqueConstraint(columnNames = {"store_id"}))
private Set<Product> products = new HashSet<>();
}        

And now after creating, your database will see the Product table has storeId as a primary key. But is a foreign key from the store table and not a primary key for the product table.

The Embeddable doesn't have a Repository because it is dependent on the entity for example the product embeddable is dependent on the store entity. and we can insert it without the use of the Store Repository.

The difference between both approaches:

Entity:

When creating an entity you can relate it with the JPA repository to write your query or use the build-in query from JPA.

Embeddable:

When creating an embeddable class must relate to any entity class, because it is dependent on the entity class. and we cant create a repository.

Conclusion:

Each application has data and this data will be used inside the programming for a display to the application client, and because of that we have a database, Jpa, and hibernate.

But how we can design the database, is dependent on the business logic for the application.

References:

要查看或添加评论,请登录

Abd-Alrhman Alkraien的更多文章

  • Base Entity and Audit entity with?JPA

    Base Entity and Audit entity with?JPA

    Introduction: When creating any web application and wanting to connect it with DB, we will add id as a column inside…

    1 条评论
  • Java 8 — Stream APIs

    Java 8 — Stream APIs

    overview When Java 8 came into this world, it comes to provide us with more features, flexibility, and comfortable to…

  • Java with Jackson and JSON

    Java with Jackson and JSON

    Introduction: every developer knows about JSON, and many developers use Json format with API requests or responses. So…

    2 条评论
  • Liquibase Tutorial

    Liquibase Tutorial

    Introduction: Sometimes we need to create a database and put fake data inside it, when running the application, we can…

    1 条评论
  • Java history from Java 1.0 to Java 18

    Java history from Java 1.0 to Java 18

    Introduction: From this article, you can see the version of java from the first to the latest version. And what are the…

  • Immutability in Java

    Immutability in Java

    What is Immutability?!! An object is considered immutable if its state cannot change after it is constructed. Maximum…

    2 条评论
  • Logging Spring requests using aspect

    Logging Spring requests using aspect

    Introduction: In any web application we need logging request and response, We can do it using Log4j in java, but in…

  • Aspect Object Programing with Spring boot?Example

    Aspect Object Programing with Spring boot?Example

    Introduction: In the previous article, we talked about Aspect and if you read the previous article you should know the…

  • Aspect object programming with Spring?boot

    Aspect object programming with Spring?boot

    Introduction: The programming in the world is changing every day and the projects are bigger in the last few days. so…

    1 条评论
  • Spring Application and Parent maven Pom

    Spring Application and Parent maven Pom

    Introduction: When we want to create a new web application using spring boot, ensure we need used maven to use some…

    1 条评论

社区洞察

其他会员也浏览了