What correct annotation for this situation. JPA. Hibernate - java

I would create table, which contains objects. Objects should displayed like columns in table. (+ public, - private)
+Company
-int companyId
-String companyName
-Set<Department> listOfDepartments = new HashSet<Department>();
+Department
-int departmentId
-String departmentName
-Set<Worker> listOfWorkers = new HashSet<Worker>();
+Worker
-int workerId
-String workerName
My unsuccessful attempt:
#XmlRootElement(name="Company")
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Table(name="Company")
public class Company {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#XmlAttribute (name="id")
#Column (name="idCompany")
private int idCompany;
#XmlElement(name="companyName")
#Column (name="companyName")
private String companyName;
#XmlElement (name = "YYY")
#ElementCollection
private Set<Department> listOfDepartments = new HashSet<Department>();
#XmlRootElement(name="Department")
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Embeddable
#Table(name="Department")
public class Department {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#XmlAttribute(name="idDepartment")
#Column (name="idDepartment")
private int idDepartment;
#XmlElement(name="departmentName")
#Column (name="deparmentName")
private String departmentName;
#XmlElement (name = "XXX")
#ElementCollection
private Set<Worker> listOfWorkers = new HashSet<Worker>();
#XmlRootElement(name="Worker")
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Embeddable
#Table(name="Worker")
public class Worker {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#XmlAttribute(name="idWorker")
#Column (name = "idWorker")
private int idWorker;
#XmlElement(name="workerName")
#Column (name = "workerName")
private String workerName;
Advise the correct annotation for this situation. I will appreciate.
UPDATE:
companyId|companyName|deptId|deptName|workerId|workerNam|
1|'Lala'|1|'Logical'|1|'Jason'|
1|'Lala'|1|'Logical'|2|'Bason'|
1|'Lala'|2|'Chemical'|1|'Cason'|
1|'Lala'|2|'Chemical'|2|'Dason'|

If there is some constraint that you want to save all object(entities) in one table in your case company(but the best practice is a normal data base design you should consider company department and workers in separate tables) you have redundancy in data and your table data seems like this...
1 comp1 1 dep1 1 worker1
1 comp1 1 dep1 2 worker2
1 comp1 2 dep2 3 worker3
then correct jpa annotation is:
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Table(name="company")
public class Company{
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#XmlAttribute(name="idComapny")
#Column (name="idCompany")
private int idcompany;
#XmlElement(name="companyName")
#Column (name="companyName")
private String companyName;
**#Embedded**
private Department department;
**#Embedded**
private Worker worker;//can be removed and put in Department but result is the same
......
and put annotation #Embeddable on top of Department Entity and Worker Entity.
#XmlRootElement(name="Department")
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Embeddable
#Table(name="Department")
public class Department {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#XmlAttribute(name="idDepartment")
#Column (name="idDepartment")
private int idDepartment;
#XmlElement(name="departmentName")
#Column (name="deparmentName")
private String departmentName;

Related

how to use #OrderBy with Embeddable in spring boot jpa

I have 3 entity Unit, Off, Position. in my Unit have an constrain one to many with list offs, off have position. I want to Order by code in position.code, how can I make it
#Entity
#Table(name = "unit")
public class Unit{
#Id
#Column(name = "id")
private Long id;
#OneToMany(fetch = FetchType.LAZY)
#JoinClolumn(name = "unit")
#ElementCollection
#OrderBy("position.code")
private List<Off> offs;
}
this is my Entity Off
#Entity
#Table(name = "off")
#Embeddable
public class Off{
#Id
#Column(name = "id")
private Long id;
#Column(name = "cate_position")
private Long catePosition;
#ManyToOne
#NotFound(action = NotFoundAction.IGNORE)
#JoinClolumn(name = "cate_position")
#Embedded
private Position position;
}
this is my Entity Position
#Entity
#Table(name = "position")
#Embeddable
public class Position{
#Id
#Column(name = "id")
private Long id;
#Column(name = "code")
private String code;
}
How can I sort List offs in Unit entity by 'position.code', it always throws invalid column name 'position'. Many thanks!
Annotate the entity class Off with #Embeddable
and now include the following code above the List
#ElementCollection
#OrderBy("position.code DESC")
private List<Off> offs;

Java JPA how relate an entity instance with all instances of another entity?

I work with an embedded H2 database in which I use the #OneToMany relationship to relate an entity instance (product) to multiple instances of the other entities (suppliers); it's useful when I have specific suppliers for a particular product.
However now, I want to associate all the suppliers with every single product; I don't want to generate in my supplier table different supplier records for each product, instead I want to have only 5 records (5 suppliers) in my supplier table which are associated to every single product, it few words I want to achieve something like "one to all", is it possible to do it using JPA annotations?
Product entity
#Entity
public class Product {
#Id
private String productCode;
#OneToMany
#JoinColumn(name = "supplier_id", referencedColumnName = "productCode")
private List<Supplier> suppliers;
}
Supplier entity
#Entity
public class Supplier {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String name;
}
Unidirectional #OneToMany association:
#Entity
public class Product {
#Id
// #Column(name = "id") maybe
// #GeneratedValue maybe
private String productCode;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) // according to your need
private List<Supplier> suppliers;
...
}
And,
#Entity
public class Supplier {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
...
}
#ManyToOne association:
#Entity
public class Product {
#Id
// #Column(name = "id") maybe
// #GeneratedValue maybe
private String productCode;
...
}
And,
#Entity
public class Supplier {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name = "product_id", foreignKey = #ForeignKey(name = "PRODUCT_ID_FK"))
private Product product;
private String name;
...
}

Override column names of embedded id

I have an entity:
#Entity
#Table(name = "person")
public class Person {
#EmbeddedId
private PersonId id;
#OnDelete(action = OnDeleteAction.CASCADE)
#MapsId("a_phoneNumberId")
#ManyToOne
private PhoneNumber phoneNumber;
#OnDelete(action = OnDeleteAction.CASCADE)
#MapsId("b_addressId")
#ManyToOne
private Address address;
...
with embedded id:
#Embeddable
public class PersonId implements Serializable {
private int a_phoneNumberId;
private int b_addressId;
...
Note: a_ and b_ prefixes are used to order columns in primary key.
Everything works as expected and hibernate generates a table with columns: phoneNumber_id and address_id.
Is it possible to rename those columns, as I want to have a snake_case name - phone_number_id?
So far I tried
#AttributeOverride annotation:
#Entity
#Table(name = "person")
public class Person {
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "a_phoneNumberId", column = #Column(name = "phone_number_id"))
})
private PersonId id;
#Column annotation for the id:
#Embeddable
public class PersonId implements Serializable {
#Column(name = "phone_number_id")
private int a_phoneNumberId;
but it changed nothing.

Hibernate: How to join attribute with condition using a third table

I have the following tables ...
Object1
-------
id
...
Object2
-------
id
...
AttributeValue
--------------
id
attribute_id
object_id
value
Attribute
---------
id
name
type
... and entity classes
#Entity
#Table(name = "Attribute")
public class Attribute {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "type")
private String type;
}
#Entity
#Table(name = "AttributeValue")
public class AttributeValue {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "attribute_id")
private Long attributeId;
#Column(name = "object_id")
private Long objectId;
#Column(name = "value")
private String value;
}
#Entity
#Table(name = "Object1")
public class Object1 {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// ...
// how to annotate to get all matching attribute values?
private Set<AttributeValue> values;
}
I want hibernate to fill the values instance variable with all AttributeValues that have the corresponding object_id and an attribute type of object1.
If it was only about the criterium of object_id, I would write e.g.
#JoinColumn(insertable = false, updatable = false, name = "object_id")
private Set<AttributeValue> values;
But in this case it would fill in also the values with type object2etc.
So my question is: Is this semantic expressible in Hibernate and if so, how?
EDIT: I want to highlight that the goal is to have multiple Objects (here Object1, Object2, ... ObjectN) that have no common hierarchy, but all share the feature of having attributes. The attributes for all objects will reside in one table, distinguished by some sort of discriminator (here exemplarily type).
I think the object must be:
#Entity
#Table(name = "AttributeValue")
public class AttributeValue {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "attribute_id")
private Long attributeId;
#ManyToOne
    #JoinColumn(name="object_id", nullable=false)
private Object1 object1;
#Column(name = "value")
private String value;
}
#Entity
#Table(name = "Object1")
public class Object1 {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy="object1")
private Set<AttributeValue> values;
}
Hibernate will be generate only object_id column on AttributeValue table.

How to convert this UML to JPA entities

I have this UML diagram.
And I tried to build entities like this (I renamed Entity class to Entidad)
RelationshipType.java
#Entity
#Table(name = "relationship_type")
public class RelationshipType {
#Id
#GeneratedValue
private Long id;
private String type;
#OneToMany(mappedBy = "relationshipType", fetch = FetchType.EAGER)
private Set<Relationship> relationships = new HashSet<Relationship>();
//Getters and Setters
Relationship.java
#Entity
#Table(name = "relationship")
public class Relationship {
#Id
#ManyToOne
private RelationshipType relationshipType;
#Id
#ManyToOne
private Entidad entity;
//Getters and Setters
Entidad.java
#Entity
#Table(name = "entity")
public class Entidad {
#Id
#GeneratedValue
private Long id;
private String image;
private String foundationNotes;
private String alias;
private Boolean excludeNotifications;
private String notes;
//[...]
#ManyToOne
private Relationship related;
#OneToMany(mappedBy = "entity", fetch = FetchType.EAGER)
private Set<Relationship> relationships = new HashSet<Relationship>();
But when I launch app throws this:
Foreign key (FK_9d8afoh1pv9r59iwjkbcpnud1:entity [])) must have same number of columns as the referenced primary key (relationship [relationshipType_id,entity_id])
At now, I don't know where is the problem and need do this well because I'm using this entities to build the DB schema.

Categories

Resources