Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: how to composite an entity from columns of multiple tables (not save an entity to mulitple tables)

I have two entities:

@Entity
@Table(name="TableA")
public class TableA {
     @Id
     @Column(name="id")
     long id;

     @Column(name="tableB_id")
     long tbId;

     @Column(name="column1", table="TableB")
     String tbColumn1; 
}

@Entity
@Table(name="TableB")
public class TableB {
     @Id
     @Column(name="id")
     long id;

     @Column(name="column1")
     String column1; 
}

TableA has a foreign key 'tbId' to TableB.id. And TableB has a column named "column1", now I want to get "column1" in TableA entity by some sort of join. What's way I should go in terms of JPA? This is not OneToOne as I don't want to wire entire TableB entity in TableA.

like image 202
zx_wing Avatar asked Jul 03 '12 23:07

zx_wing


People also ask

How do you map an entity to multiple tables?

Yes, you can map an entity to 2 database tables in 2 simple steps: You need to annotate your entity with JPA's @Table and @SecondaryTable annotations and provide the names of the first and second table as the value of the name parameters.

How do I join two entities in JPA?

The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.

How do you map entity to a table?

In Spring Data JPA we can map an entity to a specific table by using @Table annotation where we can specify schema and name. But Spring Data JDBC uses a NamingStrategy to map an entity to a table name by converting the entities class name.

Which of the following annotation is used in JPA to link two tables through a relation?

The @JoinTable annotation is used to specify the table name via the name attribute, as well as the Foreign Key column that references the post table (e.g., joinColumns ) and the Foreign Key column in the post_tag link table that references the Tag entity via the inverseJoinColumns attribute.


1 Answers

If you want to group columns within one object only for reading data I suggest you two ways:

  1. Creating DB VIEW and map it as an Entity.
  2. Using Result Classes Constructor Expression, it will instantiate and populate objects of provided class based on results query return.

From ObjectDB on Result Classes Constructor Expression:

JPA supports wrapping JPQL query results with instances of custom result classes. This is mainly useful for queries with multiple SELECT expressions, where custom result objects can provide an object oriented alternative to representing results as Object[] elements.

like image 138
JMelnik Avatar answered Oct 04 '22 03:10

JMelnik