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.
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.
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.
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.
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.
If you want to group columns within one object only for reading data I suggest you two ways:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With