Atypic JPA OneToOne relation - java

I have a problem using JPA.
I have to tables:
-----------------
| TableA |
|---------------|
| ID: INT |
| ... |
| ESTATUS1: INT |
| ESTATUS2: INT |
-----------------
-----------------
| EstatusTags |
|---------------|
| COD: VARCHAR |---> COD and VALUE are a concatenated PK
| VALUE: INT |
| DESC: VARCHAR |
-----------------
EstatusTags is a table to store sets of pairs [VALUE, DESC], given a COD.
Before I use JPA, I used to query this kind of data in something like this:
SELECT ID, ESTATUS1, ESTATUS2, E1.DESC DESC1, E2.DESC DESC2
FROM TABLEA A
INNER JOIN ESTATUSTAGS E1 ON E1.COD = "a_estatus1"
AND E1.VALUE = A.ESTATUS1
INNER JOIN ESTATUSTAGS E2 ON E2.COD = "a_estatus2"
AND E2.VALUE = A.ESTATUS2
I'm trying to use JPA to model this using two entity classes:
#Entity
#Table(name = "EstatusTags")
public class EstatusTags implements Serializable {
#EmbeddedId
private ValueTagPK id;
#Column(name="VVA_DESC")
private String desc;
#Column(name="VVA_ORDEN")
private Integer orden;
}
#Entity
#Table(name = "TableA")
public class A implements Serializable {
#Column(name="ID")
private String desc;
#OneToOne(???)
private EstatusTag estatus1;
#OneToOne(???)
private EstatusTag estatus2;
}
I have strong doubts in how to model the relations. Can it be done with annotations? There is necesary the JPQL use to fit this structure?
I hope somebody could help me with this.
Thanks a lot.

The problem is that your entity model does not match the table structure.
In your entity model you have a one to one relation ship between A and EstatusTag whereas in your table model you have a relationship of one A and multiple Estatustags (for one value there may exist multiple Etatustags entries)
You overcome the problem that Table A does not have a cod column by adding something like a virtual cod column E1.COD = "a_estatus1" to your SQL Query.
What you can do is you map the value column of to two properties of EstatusTag one time to the composite pk and the other time to a single property in the following way . The simple value is made accessible via property access but marked as not updatable not insertable also the setter does not really work and is made private.
Remark: I don't know if that works with all JPA implementations - Tested with hibernate 4.3.8.
#Entity
#Table(name = "EstatusTags" )
#Access(AccessType.FIELD)
public class EstatusTag implements Serializable{
private #EmbeddedId ValueTagPK id;
#Column(name="VVA_DESC")
private String desc;
#Column(name="VVA_ORDEN")
private Integer orden;
#Column(name="value", updatable=false, insertable=false)
#Access(AccessType.PROPERTY)
public int getValue() {
return id.value;
}
private void setValue(int value) {
// only because otherwise hibernate complains about a missing setter.
}
}
#Entity
#Table(name = "TableA")
public class A implements Serializable{
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.TABLE)
private int id;
#OneToOne()
#JoinColumn(name="estatus1",referencedColumnName="value")
public EstatusTag estatus1;
#OneToOne()
#JoinColumn(name="estatus2",referencedColumnName="value")
public EstatusTag estatus2;
}

Related

Is there any way to put not Base Type in Entity?

I have an entity like this:
#Entity
public Asset extends BaseEntity {
private String name;
private Localization currentLocalization;
private Localization plannedLocalization;
}
It throws Basic attribute type should not be 'Persistence Entity'.
I know that Entity should have Id etc, but what if I dont want to create another table, service, repository just for Localization who should be just a property, not another table.
Edit:
Localization:
#Embeddable
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
public class Localization {
#OneToOne(targetEntity = Floor.class, fetch = FetchType.LAZY)
#JoinColumn(name = "FLOOR_ID")
private Floor floor;
#Min(0)
#Max(1000)
private int xAxis;
#Min(0)
#Max(2400)
private int yAxis;
#Min(0)
#Max(999)
private int zAxis;
}
Here I am using #Embedded with Attribute Overrides like:
#Embedded
private Localization localization;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="floor.id", column = #Column(name = "floor_plannedId"))
})
private Localization localizationPlanned;
but it throws:
Repeated column in mapping for entity: com.mrfisherman.relice.Entity.Asset.AssetEntity column: floor_id (should be mapped with insert="false" update="false")
No matter how I set name in #AttributeOverride
The error is due that Localization is not of any "basic type" that is directly mappable to any database column type. So it should either be an entity and fields of type Localization mapped with #OneToOne or #ManyToOne.
But you do not want another entity so the other option is to make it #Embeddable.
Assume your Localization is like:
#Getter #Setter
public class Localization {
private String str;
private Integer num;
}
You can flatten fields inLocalization to the containing class by annotating it like:
#Embeddable
public class Localization { ...
and in your Asset tell that this field should be embedded:
#Embedded
private Localization currentLocalization;
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "str", column = #Column(name = "str2")),
#AttributeOverride(name = "num", column = #Column(name = "num2"))
})
private Localization plannedLocalization;
This would result into a table like:
Table "public.asset"
Column | Type | Collation | Nullable | Default
--------+------------------------+-----------+----------+---------
id | bigint | | not null |
num | integer | | |
str | character varying(255) | | |
name | character varying(255) | | |
num2 | integer | | |
str2 | character varying(255) | | |
As you see in the table, it is now flatten. And you also see that because there is two Localization in your Asset you need to do something with the clashing column names.
currentLocalization can use default naming but plannedLocalization cannot because currentLocalization already reserved those column names. So that is why there is a need for attribute override.
Considering all this you might evaluate again whether you create yet another entity and use #OneTOne or #ManyToOne mappings. It depends how compled your Localization is.

Composite discriminator jpa

I'm getting extra DTYPE in my query while my jps entities are structured as follow:
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="PRODUCT_TYPE")
public abstract class Product extends Tent implements Serializable {
##ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "PRODUCT_TYPE")
private TransType transType;
...
}
#Entity
#Table(name="CAR")
#DiscriminatorColumn(name="CAR_TYPE")
public class Car extends Product {
#Column(name = "car_ent_id", insertable = false, updatable = false)
private int carEntId;
....
}
Tent
|
Product
|
LEVEL-1 -->[Car_1_1] [car_1_2]....
|
LEVEL-2 -->[car_2_1] [car_2_2]...
So what I'm trying to achieve, discriminate all the entities at both LEVEL-1 and 2 together. Abstract class Product is having type which discriminating immediately 1 level down but when we are further extending level 1 entities at level 2. This's where I'm not having any clue.
Can we have custom non-db field defined in Product and assigning a value to each level-1 entity and for level-2 entities TYPE can work somehow?
Not really having any clue
Thanks

Multi valued attribute in Hibernate

I have the following entities:
____________________ ____________________
| Activity | | Benefit |
------------------ | |------------------|
| activityId:long |-------------| benefitId: long |
| activity:varchar | | activityId: long |
| .... | | benefit: varchar |
-------------------- -------------------|
Can I map this into Hibernate so I end up with this:
#Entity
class Activity {
#Id
private Long id;
private String activity;
private List<String> benefits;
}
Yes, you can use the #ElementCollection tag.
Here's what your code would look like:
#Entity
#Table(name = "Activity")
class Activity {
#Id
#Column(name="activity_id")
private Long id;
#Column(name = "name")
private String activity;
#ElementCollection
#CollectionTable(
name = "Benefit",
joinColumns = #JoinColumn(name = "activityId")
)
private List<String> benefits;
}
Though I would call the table ActivitiesBenefits instead of Benefit to make it clear that that table will store pairs of activities and benefits. Also, there is no need for a benefitId, since a benefit is a weak entity (it cannot exist without an activity), so you can drop that too.
Reference: https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
Hi I could find one way in which you could do it. Below is code for same.
#Entity
#Table(name = "Activity")
class Activity {
#Id
#Column(name="activity_id")
private Long id;
#Column(name = "name")
private String activity;
#OneToMany
#Formula("(select CONCAT(benefitId, activityId, benefit) from Benefit b where b.activityId = activity_id)")
private List<String> benefits;
}
I am using a sql returning list of benefits and then concatenate it and store it in our benefits list.
The string in formula is SQL(not HQL) so its column names and not filed member names.

#OneToMany relationship using a single #JoinColumn?

I have the following tables (most essential columns shown only, A & B are not the real names btw):
table A {
...
}
table B {
...
}
table METADATA {
KEY
VALUE
REF_A
REF_B
}
METADATA holds additional key/value meta data for both table A & B. The key/value is needed as we have to handle dynamic data for which we cannot up front create columns for in A and B.
The entities are setup as (JPA using hibernate as provider):
interface Entity {
...
getId()
...
}
class A implements Entity {
...
#OneToMany(cascade = {ALL}, mappedBy = "a", orphanRemoval = true, fetch = LAZY)
private List<MetaData> metaData;
...
#Override
public List<MetaData> getMetaData() {
return metaData;
}
...
}
class B implements Entity {
...
#OneToMany(cascade = {ALL}, mappedBy = "b", orphanRemoval = true, fetch = LAZY)
private List<MetaData> metaData;
...
#Override
public List<MetaData> getMetaData() {
return metaData;
}
...
}
class MetaData implements Entity {
...
#ManyToOne
#JoinColumn(name = "REF_A", nullable = true)
private A a;
#ManyToOne
#JoinColumn(name = "REF_B", nullable = true)
private B b;
...
}
This setup works fine. However we have run into issues on some databases (for instance DB2) with a unique index we create (to ensure a meta key is only used once for a given row in A or B):
CREATE UNIQUE INDEX METADATA_UNIQUE_KEY ON METADATA (METAKEY, REF_A, REF_B)
as creating the index requires requires that all columns are non-null. This is not the case for use with the above design as the domain logic will either be that the meta data is set on A or B, hence one of these will always be null.
Possible solutions of course are to split the METADATA into two tables, one for A and one for B. However I would prefer to keep one table and instead just have one "REF" column which would either be an A or B as well as a TYPE column to say whether it's a meta data for an A or B. The TYPE would be needed as we have separate sequences for id for each table and a A and B could get the same technical id and hence get mixed up data otherwise.
My question is - is there any way to set this up with JPA?
For one-table based inheritance there is a #DiscriminatorValue which can be used to distinguish the specific stored sub-class, can this be used here as well? I am looking for something like:
table A {
...
}
table B {
...
}
table METADATA {
KEY
VALUE
REF
TYPE
}
#DiscriminatorValue("A")
class A implements Entity {
...
#OneToMany(cascade = {ALL}, mappedBy = "entity", orphanRemoval = true, fetch = LAZY)
private List<MetaData> metaData;
...
#Override
public List<MetaData> getMetaData() {
return metaData;
}
...
}
#DiscriminatorValue("B")
class B implements Entity {
...
#OneToMany(cascade = {ALL}, mappedBy = "entity", orphanRemoval = true, fetch = LAZY)
private List<MetaData> metaData;
...
#Override
public List<MetaData> getMetaData() {
return metaData;
}
...
}
class MetaData implements Entity {
...
#ManyToOne
#JoinColumn(name = "REF", nullable = true)
private Entity entity;
#DiscriminatorColumn(name="TYPE", discriminatorType=STRING, length=20)
private String type;
...
}
so basically when a meta data is inserted for A this SQL would be used:
INSERT INTO METADATA (KEY, VALUE, REF, TYPE) VALUES ("metaKey", "metaValue", 1, "A")
Any suggestion are welcomed.
Rgs,
-Martin
I'm not sure why you need to create a key (metakey) in the metadata table, given thet the rows are already tied either to Table A or Table B.
However I think the problem is in considering the MetaData table an entity, given that its only purpose is to save some extra information of an existing entity, it means that you cannot have a row in MetaData without a row in TableA or TableB.
Instead of using relationship mapping one option is to use element collections to directly have the Map of key/value pairs in the corresponding entities:
#Entity
#Table(name="TableA")
public class TableA
{
#Id
#GeneratedValue(strategy= GenerationType.TABLE)
private int id;
#ElementCollection
#CollectionTable(name="MetaData", joinColumns={#JoinColumn(name="TableA_id")})
#MapKeyColumn(name="metaKey")
#Column(name="metaValue")
private Map<String, String> metadata;
}
#Entity
#Table(name="TableB")
public class TableB
{
#Id
#GeneratedValue(strategy= GenerationType.TABLE)
private int id;
#ElementCollection
#CollectionTable(name="MetaData", joinColumns={#JoinColumn(name="TableB_id")})
#MapKeyColumn(name="metaKey")
#Column(name="metaValue")
private Map<String, String> metadata;
}
Note that there is no java class for a "MetaData" table or entity, the table is automatically mapped from the #ElementCollection and #CollectionTable annotations.
The above mappings correspond to the following MetaData table:
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| TableA_id | int(11) | YES | MUL | NULL | |
| metaValue | varchar(255) | YES | | NULL | |
| metaKey | varchar(255) | YES | | NULL | |
| TableB_id | int(11) | YES | MUL | NULL | |
+-----------+--------------+------+-----+---------+-------+
If you prefer to keep a separate java class for MetaData to keep using a List instead of a Map, it can also be done with #ElementCollection, you just need to annotate the MetaData class with #Embeddable instead of #Entity. In that way it doesn't need an Id column like a regular entity.

Hibernate annotation many-to-one mapping generating odd schema

I have a fairly simple Many to One relationship between two classes:
#Entity
public class Schedule
implements java.io.Serializable {
private String scheduleName;
private HashSet<Step> steps;
#OneToMany(mappedBy="schedule", cascade=CascadeType.ALL,
fetch=FetchType.EAGER)
public HashSet<Step> getSteps() {
return steps;
}
}
#Entity
public class Step implements java.io.Serializable {
private Long id;
private String duration;
private String stepType;
private Schedule schedule;
#ManyToOne(fetch=FetchType.LAZY)
public Schedule getSchedule() {
return schedule;
}
#Id
#GeneratedValue
public Long getId() {
return id;
}
}
Hibernate generates the following tables (in Postgres)
Table "public.schedule"
Column | Type | Modifiers
--------------+------------------------+-----------
uuid | character varying(255) | not null
version | integer |
schedulename | character varying(255) |
steps | bytea |
Table "public.step"
Column | Type | Modifiers
---------------+------------------------+-----------
id | bigint | not null
duration | character varying(255) |
steptype | character varying(255) |
temperature | numeric(19,2) |
schedule_uuid | character varying(255) |
The step table is what I expect, but I don't understand why the steps(bytea) column is there. Am I doing something wrong in my mapping or do I just not understand how hibernate works?
I suspect the problem is that you're using a concrete HashSet instead of the Set interface. Try this (assuming it has an Id somewhere):
#Entity
public class Schedule implements java.io.Serializable {
private String scheduleName;
private Set<Step> steps = new HashSet<Step>();
#OneToMany(mappedBy="schedule", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Set<Step> getSteps() {
return steps;
}
// other properties, getters, setters
}
Also note how I initialized the steps property. Let me quote the documentation about this:
6.1. Persistent collections
...
Notice how the instance variable was
initialized with an instance of
HashSet. This is the best way to
initialize collection valued
properties of newly instantiated
(non-persistent) instances. When you
make the instance persistent, by
calling persist() for example,
Hibernate will actually replace the
HashSet with an instance of
Hibernate's own implementation of Set.
And make sure that:
both entities have an #Id property (the part you're showing is not enough to confirm that).
Step is implementing equals/hashCode correctly (see the references below).
References
Hibernate Core Reference Guide
4.3. Implementing equals() and hashCode()
6.1. Persistent collections
Update: Can't reproduce (I don't have PostgreSQL installed by I don't think it is that relevant). I used the following entities:
#Entity
public class Step implements java.io.Serializable {
private Long id;
private String duration;
private String stepType;
private Schedule schedule;
#ManyToOne(fetch = FetchType.LAZY)
public Schedule getSchedule() { return schedule; }
#Id #GeneratedValue
public Long getId() { return id; }
// getters, setters, equals, hashCode
}
And:
#Entity
public class Schedule implements java.io.Serializable {
private Long id;
private String scheduleName;
private Set<Step> steps = new HashSet<Step>();
#OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<Step> getSteps() { return steps; }
#Id #GeneratedValue
public Long getId() { return id; }
// getters, setters
}
Here is the generated DDL:
create table Schedule (
id bigint generated by default as identity (start with 1),
scheduleName varchar(255),
primary key (id)
)
create table Step (
id bigint generated by default as identity (start with 1),
duration varchar(255),
stepType varchar(255),
schedule_id bigint,
primary key (id)
)
alter table Step
add constraint FK277AEC7B775928
foreign key (schedule_id)
references Schedule
I don't even understand how you could use a HashSet in your OneToMany, Hibernate complained (as expected to be honest) when I tried:
Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: com.stackoverflow.q4083744.Schedule.steps

Categories