#OneToMany relationship using a single #JoinColumn? - java

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.

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.

Foreign key is being updated as null

I am trying to implement a bi-directional relationship using #OneToMany and #ManyToOne JPA annotation. My foreign key is being updated as NULL which is not correct. I need some input to resolve this.
I have created User and CardInfo class. I am trying to add a relationship where User can have more than one card. When I am trying to persist in database foreign key is being inserted as null.
#Entity
#Table(name = "customer_info")
#Data
#NoArgsConstructor
#AllArgsConstructor
public class User {
#Id
//#GeneratedValue
private String userId;
private String userName;
private Date dateOfBirth;
private boolean primeMember;
#OneToMany(mappedBy = "user", cascade = CascadeType.PERSIST, orphanRemoval = true)
private Set<CardInfo> paymentDetails;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="card_info")
public class CardInfo implements Serializable {
#Id
private String cardNumber;
#Id
private String cardType; // Debit, Credit
private String cardCategory; // Visa, mastercard
private Date expiryDate;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="user_id")
#EqualsAndHashCode.Include private User user;
public class DAOImpl {
#Transactional
public String addCustomer(User user) {
// User _user=new User();
// Set<CardInfo> cardData=new HashSet<>();
//
String userId=String.valueOf(Instant.now().toEpochMilli());
user.setUserId(userId);
Session session=sessionFactory.getCurrentSession();
session.persist(user);
return userId;
}
mysql> select * from card_info;
+----------+-------------+--------------+---------------------+---------+
| cardType | cardNumber | cardCategory | expiryDate | user_id |
+----------+-------------+--------------+---------------------+---------+
| CREDIT | 74959454959 | VISA | 2020-04-23 00:00:00 | NULL |
+----------+-------------+--------------+---------------------+---------+
1 row in set (0.00 sec)
user_id column should not be updated as NULL. Please correct me if understanding is not correct.
Although Cascade.PERSIST ensures that CardInfo objects will be persist together with their parent User, it is the responsibility of the application, or the object model to maintain relationships[1].
As the foreign key is in CardInfo, you have to ensure that every CardInfo is associated to the User that you are persisting. A common pattern is to add extra logic to handle both sides of the relationship in the domain object, e.g.:
public class User {
// fields, accessors and mutators
public void addPaymentDetails(CardInfo cardInfo) {
if (paymentDetails == null) {
paymentDetails = new LinkedHashSet<>();
}
if (cardInfo.getUser() != this) {
cardInfo.setUser(this);
}
paymentDetails.add(cardInfo);
}
}
The above code ensures that both sides of the relationship are in sync (i.e., if a user adds a card to its paymental details, then the card info is "owned" by the user).
Finally, while not directly related to your problem, my advice would be to make the relationship between CardInfo and User mandatory and its respective join column NOT NULL so that queries are properly optimised and no CardInfo can exist in the database without an association to its owning User:
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name="user_id", nullable = false)

Atypic JPA OneToOne relation

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;
}

How to persist two entities with JPA

I am using the JPA in my webapp and I can't figure out how to persist two new entities that relate to each other. Here an example:
These are the two entities
+-----------------+ +--------------------+
| Consumer | | ProfilePicture |
+-----------------+ +--------------------+
| id (PK) |---| consumerId (PPK+FK)|
| userName | | url |
+-----------------+ +--------------------+
The Consumer has an id and some other values. The ProfilePicture uses the Consumer's id as it's own primary key and as foreign key. (Since a ProfilePicture will not exist without a Consumer and not every Consumer has a ProfilePicture)
I used NetBeans to generate the entity classes and the session beans (facades).
This is how they look like in short
Consumer.java
#Entity
#Table(name = "Consumer")
#NamedQueries({...})
public class Consumer implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "userName")
private String userName;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")
private ProfilePicture profilePicture;
/* and all the basic getters and setters */
(...)
}
ProfilePicture.java
#Entity
#Table(name = "ProfilePicture")
#XmlRootElement
#NamedQueries({...})
public class ProfilePicture implements Serializable {
#Id
#Basic(optional = false)
#NotNull
#Column(name = "consumerId")
private Integer consumerId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "url")
private String url;
#JoinColumn(name = "consumerId", referencedColumnName = "id", insertable = false, updatable = false)
#OneToOne(optional = false)
private Consumer consumer;
/* and all the basic getters and setters */
(...)
}
So when I want to create a Consumer with his ProfilePicture I thought I would do it like this:
ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg"); // create the picture object
Consumer consumer = new Consumer("John Doe"); // create the consumer object
profilePicture.setConsumer(consumer); // set the consumer in the picture (so JPA can take care about the relation
consumerFacade.create(consumer); // the facade classes to persist the consumer
profilePictureFacade.create(profilePicture); // and when the consumer is persisted (and has an id) persist the picture
My Problem
I tried almost everything in every combination but JPA doesn't seem to be able to link the two entities on it's own. Most of the time I am getting errors like this:
EJB5184:A system exception occurred during an invocation on EJB ConsumerFacade, method: public void com.me.db.resources.bean.ConsumerFacade.create(com.mintano.backendclientserver.db.resources.entity.Consumer)
(...)
Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
As far as I understand the problem, it is because the ProfilePicture doesn't know the id of the Consumer and thus, the entities cannot persist.
The only way it ever worked, was when persisting the Consumer first, setting it's id to the ProfilePicture and then persisting the picture:
ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg"); // create the picture object
Consumer consumer = new Consumer("John Doe"); // create the consumer object
consumerFacade.create(consumer); // the facade classes to persist the consumer
profilePicture.setConsumerId(consumer.getId()); // set the consumer's new id in the picture
profilePictureFacade.create(profilePicture); // and when the consumer is persisted (and has an id) persist the picture
However these two tables are just an example and naturally the database is much more complex and setting the ids manually like this seems very inflexible and I am afraid of over complicating things. Especially because I can't persist all entities in one transaction (which seems very inefficient).
Am I doing it right? Or is there another, more standard way?
Edit: my solution
As FTR suggested, one problem was the missing id for the ProfilePicture table (I used the Consumer.id as foreign and primary)..
The tables look like this now:
+-----------------+ +--------------------+
| Consumer | | ProfilePicture |
+-----------------+ +--------------------+
| id (PK) |_ | id (PK) |
| userName | \_| consumerId (FK) |
+-----------------+ | url |
+--------------------+
Then Alan Hay told me to Always encapsulate add/remove to relationships and then you can ensure correctness, which I did:
Consumer.java
public void addProfilePicture(ProfilePicture profilePicture) {
profilePicture.setConsumerId(this);
if (profilePictureCollection == null) {
this.profilePictureCollection = new ArrayList<>();
}
this.profilePictureCollection.add(profilePicture);
}
Since ProfilePicture has it's own id now, it became a OneToMany relationship, so each Consumer can now have many profile pictures. That's not what I intended at first, but I can life with it :) Therefore I can't just set a ProfilePicture to the Consumer but have to add it to a collection of Pictures (as above).
This was the only additional method I implemented and now it works. Thanks again for all your help!
When persisting an instance of the non-owning side of the relationship (that which contains the 'mappedBy' and in your case Consumer) then you must always ensure both sides of the relationship are set to have cascading work as expected.
You should of course always do this anyway to ensure your domain model is correct.
Consumer c = new Consumer();
ProfilePicure p = new ProfilePicture();
c.setProfilePicture(p);//see implementation
//persist c
Consumer.java
#Entity
#Table(name = "Consumer")
#NamedQueries({...})
public class Consumer implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "userName")
private String userName;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")
private ProfilePicture profilePicture;
public void setProfilePicture(ProfilePicture profilePicture){
//SET BOTH SIDES OF THE RELATIONSHIP
this.profilePicture = profilePicture;
profilePicture.setConsumer(this);
}
}
Always encapsulate add/remove to relationships and then you can ensure correctness:
public class Parent{
private Set<Child> children;
public Set<Child> getChildren(){
return Collections.unmodifiableSet(children); //no direct access:force clients to use add/remove methods
}
public void addChild(Child child){
child.setParent(this);
children.add(child);
}
public class Child(){
private Parent parent;
}
You can persist one object and its child at a time. So I think this should work:
ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg"); // create the picture object
Consumer consumer = new Consumer("John Doe"); // create the consumer object
consumer.setProfilePicture(profilePicture);
consumerFacade.create(consumer);

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