Java JPA with DiscriminatorColumn - java

I have a problem with DiscriminatorColumn and DiscriminatorValue.
My expectation is :
-TypeOne, TypeTwo, TypeThree are options related to the User.
-A user can have TypeOne only 1 row.
-A user can have TypeTwo or TypeThree multiple rows.
-I used Pageable for search criteria and sorting by typeOneEntity.optionCode
User table.
|id|user_id|
|-|-|
|1114|a#a.com|
UserOption table.
|id|user_id|option_code|option_type_name|
|-|-|-|-|
|1|1114|CODE_1|TYPE_1|
|2|1114|CODE_2|TYPE_2|
|3|1114|CODE_3|TYPE_2|
|4|1114|CODE_4|TYPE_3|
Ps. User.id = UserOption.user_id
I have to create three entities map to this data.
#Entity
#Table(name = "user")
public class User{
#Column()
private Long id;
#Column()
private String userId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id", referencedColumnName = "user_id", insertable = false, updatable = false)
private TypeOne typeOneEntity;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id", referencedColumnName = "user_id", insertable = false, updatable = false)
private Set<TypeTwo> typeTwoEntities;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id", referencedColumnName = "user_id", insertable = false, updatable = false)
private Set<TypeThree> typeThreeEntities;
}
#Table(name = "user_option")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "option_type_name")
public abstract class UserOption{
#Column
private Long id;
#Column(name = "user_id", nullable = false)
private Long userId;
#Column
private String optionCode;
}
#Entity
#DiscriminatorValue(value = "TYPE_1")
public class TypeOne extends UserOption {
}
#Entity
#DiscriminatorValue(value = "TYPE_2")
public class TypeTwo extends UserOption {
}
#Entity
#DiscriminatorValue(value = "TYPE_3")
public class TypeThree extends UserOption {
}
After I build and try to find data, I found two issues.
1.On typeOneEntity(#OneToOne) is null.
2.On #OneToMany : I got this error ORA-01722: invalid number (error message from Hibernate)
This Entity model that I create it correct or not?
Or it need to change entity model.

Related

Extra columns in hibernate Many to Many Mapping

I need to add two extra columns (Status, createdby) in Users_Reports table.which has many to many relationship with Users and Reports tables.
TABLE STRUCTURE OF Users TABLE.
#Entity
#Table(name="Users")
#DynamicUpdate
#DynamicInsert
public class DBUsers {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID", updatable = false, insertable = false)
private int ID;
#Column(name="code", length=20)
private String code;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "Users_Reports",
joinColumns = {
#JoinColumn(name = "ID")},
inverseJoinColumns = {
#JoinColumn(name = "reportid")})
public List<DBReports> dBReports;
}
TABLE STRUCTURE OF Reports TABLE
#Entity
#Table(name="Reports")
public class DBReports{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="REPORTID")
private int reportid;
#Column(name="REPORTDATA", length=200)
private String reportdata;
#ManyToMany(mappedBy="dBReports",fetch = FetchType.LAZY)
private List<DBUsers> dBUsers;
}

Got java "stackoverflow" when join two tables

I have two java entity classes :
#Table(name = "user")
public class UserEntity
{
#Id
#Column(name = "id", unique = true, nullable = false)
private Long id;
#OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
#JoinColumn(name = "opportunity_id")
private OpportunityEntity opportunity;
}
and
#Table(name = "opportunity")
public class OpportunityEntity
{
#Id
#Column(name = "id", unique = true, nullable = false)
private Long id;
#OneToMany
#JoinColumn(name = "opportunity_id")
private List<UserEntity> users;
#OneToOne
#JoinColumn(name = "mainuser_id")
private UserEntity mainUser;
}
When i search for a list of Users [find users], i've got a "stackoverflow" when mapping User.opportunity.
the bug was clear that the opportunity.mainUser refer to User which itself refer to the same opportunity.
Is there another way to design my models ?
For example create a boolean isMain in User Model ?
Try to specify relationship to UserEntity by adding mappedBy to annotatation
#Table(name = "opportunity")
public class OpportunityEntity
{
#Id
#Column(name = "id", unique = true, nullable = false)
private Long id;
#OneToMany
#JoinColumn(name = "opportunity_id")
private List<UserEntity> users;
#OneToOne(mappedBy="opportunity")
#JoinColumn(name = "mainuser_id")
private UserEntity mainUser;
}

How to map only single column with hibernate?

I want to join a single column from another table to one of my #Entity classes:
Currently it works as follows:
#Entity
public class Product {
#Id
private long id; //autogenerated
String type; //used for mapping
#ManyToOne
#JoinColumn(name = "type", insertable = false, updatable = false)
ProductMapping mapping;
}
#Entity
public class ProductMapping {
#Id
String type;
String longname;
}
Question: how could I replace the #ManyToOne mapping to directly map to String longname?
//TODO: how to directly map to 'mapping.longname'?
#JoinColumn(name = "type", insertable = false, updatable = false)
String mapping.longname;
You can use #Formula annotation with a query like this :
#Formula("(select pm.longname from product_mapping pm where pm.COL_NAME = value)")
private String longName;
//give the column name of type from product_mapping table
OR
You can also use the below approach :
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "type", referencedColumnName = "COL_NAME", insertable = false, updatable = false)
ProductMapping mapping;
The other entity use #NaturalId annotation on the field.
#Entity
public class ProductMapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
String type;
#NaturalId
#Column(name = "SOME_VALUE")
String longname;
}

Issue on hibernate oneToMany with spring boot and postgres

I have an issue with hibernate and postgres using spring boot.
When I run the application I see in postgres logs these errors(without any data bootstrap):
2021-06-25 13:55:31.057 UTC [81] ERROR: constraint "uk_j1xiaxeat9b5r1qs27ei0t2a6" of
relation "process_template_base_environmental_impact" does not exist
2021-06-25 13:55:31.057 UTC [81] STATEMENT: alter table
process_template_base_environmental_impact drop constraint
UK_j1xiaxeat9b5r1qs27ei0t2a6
2021-06-25 13:55:31.062 UTC [81] ERROR: constraint "uk_9568qjc94suvuskoi9o2li3er" of
relation "process_template_elementary_flow_template" does not exist
2021-06-25 13:55:31.062 UTC [81] STATEMENT: alter table
process_template_elementary_flow_template drop constraint
UK_9568qjc94suvuskoi9o2li3er
2021-06-25 13:55:31.064 UTC [81] ERROR: constraint "uk_dy1ej2j9qxeoq6ca641tpfxr5" of
relation "process_template_flow_template" does not exist
2021-06-25 13:55:31.064 UTC [81] STATEMENT: alter table
process_template_flow_template drop constraint UK_dy1ej2j9qxeoq6ca641tpfxr5
I have an entity called ProcessTemplate with ProcessTemplateId as compositeKey, and 3 cascades on ElementaryFlowTemplate, BaseEnvironmentalImpact, and FlowTemplate.
ProcessTemplate:
#Data
#Entity
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
#Table(name = "process_template")
public class ProcessTemplate {
#EmbeddedId
#EqualsAndHashCode.Include
private ProcessTemplateId id;
#ManyToOne
#JoinColumn(name = "fk_process_base", referencedColumnName = "id")
private ProcessBase processBase;
#ManyToOne
#JoinColumn(name = "fk_reference_flow_base", referencedColumnName = "id")
private FlowBase referenceProduct;
#OneToMany(cascade = CascadeType.ALL)
private Set<BaseEnvironmentalImpact> baseEnvironmentalImpacts;
#OneToMany(cascade = CascadeType.ALL)
#OrderBy("impactsContribute DESC" )
private Set<FlowTemplate> flowsTemplate;
#OneToMany(cascade = CascadeType.ALL)
#OrderBy("impactsContribute DESC" )
private Set<ElementaryFlowTemplate> elementaryFlowsTemplate;
#ManyToOne
#JoinColumn(name = "fk_source_info", referencedColumnName = "id")
private SourceInfo sourceInfo;
#Column(name = "version")
#Version
private Long version;
}
ProcessTemplateId:
#Embeddable
public class ProcessTemplateId implements Serializable {
#Column(name = "process_base_id")
private UUID processBaseId;
#Column(name = "reference_product_id")
private UUID referenceProductId;
public ProcessTemplateId() {
}
public ProcessTemplateId(UUID processBaseId, UUID referenceProductId) {
this.processBaseId = processBaseId;
this.referenceProductId = referenceProductId;
}
public UUID getProcessBaseId() {
return processBaseId;
}
public UUID getReferenceProductId() {
return referenceProductId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ProcessTemplateId)) return false;
ProcessTemplateId that = (ProcessTemplateId) o;
return Objects.equals(getProcessBaseId(), that.getProcessBaseId()) &&
Objects.equals(getReferenceProductId(), that.getReferenceProductId());
}
#Override
public int hashCode() {
return Objects.hash(getProcessBaseId(), getReferenceProductId());
}
}
AbstractFlowTemplate:
#Data
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractFlowTemplate {
#Id
#EqualsAndHashCode.Include
private String id;
#Enumerated(EnumType.STRING)
private FlowType flowType;
#ManyToOne
#JoinColumn(name = "fk_source_info", referencedColumnName = "id")
private SourceInfo sourceInfo;
#Column(name = "version")
#Version
private Long version;
}
ElementaryFlowTemplate:
#Data
#Entity
#EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
#Table(name = "elementary_flow_template")
public class ElementaryFlowTemplate extends AbstractFlowTemplate {
#ManyToOne
#JoinColumn(name = "fk_elementary_flow_base", referencedColumnName = "id")
private ElementaryFlowBase elementaryFlowBase;
}
FlowTemplate (linkedProcessTemplate is not the bidirectional relation to ProcessTemplate but another unidirectional relation, because each flowTemplate had a link to another ProcessTemplate):
#Data
#Entity
#EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
#Table(name = "flow_template")
public class FlowTemplate extends AbstractFlowTemplate {
#ManyToOne
#JoinColumn(name = "fk_flow_base", referencedColumnName = "id")
private FlowBase flowBase;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumns({#JoinColumn(name = "process_base_id", referencedColumnName =
"process_base_id"),
#JoinColumn(name = "reference_product_id", referencedColumnName =
"reference_product_id")})
private ProcessTemplate linkedProcessTemplate;
}
BaseEnvironmentalImpact:
#Data
#Entity
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
#Table(name = "base_environmental_impact")
public class BaseEnvironmentalImpact {
#Id
#EqualsAndHashCode.Include
private String id;
private double value;
#ManyToOne
#JoinColumn(name = "fk_methodology", referencedColumnName = "id")
private Methodology methodology;
#ManyToOne
#JoinColumn(name = "fk_impact_category", referencedColumnName = "id")
private ImpactCategory impactCategory;
#ManyToOne
#JoinColumn(name = "fk_impact_indicator", referencedColumnName = "id")
private ImpactIndicator impactIndicator;
#ManyToOne
#JoinColumn(name = "fk_source_info", referencedColumnName = "id")
private SourceInfo sourceInfo;
#Column(name = "version")
#Version
private Long version;
//ref
#ManyToOne
#JoinColumn(name = "fk_elementary_flow_base")
private ElementaryFlowBase elementaryFlowBase;
#ManyToOne
#JoinColumns({
#JoinColumn(
name = "process_base_id",
referencedColumnName = "process_base_id"),
#JoinColumn(
name = "reference_product_id",
referencedColumnName = "reference_product_id")
})
private ProcessTemplate processTemplate;
}
As I wrote I cannot understand why I had an errors log, probably I make a mistake in the relation or cascade but I'm not able to figure out the issue. If I import data they seem correctly inserted so I cannot understand the problem.
Thanks in advance for the help.
SOLVED, EDIT:
I solve only the error on ProcessTemplate-BaseEnvironmentalImpact adding a mappedBy.
I don't include a schema because I think it's autogenerated, I include these parameters in application properties:
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true
spring.jpa.hibernate.ddl-auto = create-drop
logging.level.org.hibernate = ERROR
spring.jpa.generate-ddl = true
I also solved other issues adding:
#JoinColumns({
#JoinColumn(name = "fk_pt_process_base_id", referencedColumnName = "process_base_id"),
#JoinColumn(name = "fk_pt_reference_product_id", referencedColumnName = "reference_product_id")
} )

#JoinColumnsOrFormulas cause n+1 issue

I am facing the n+1 query issue when I use #JoinColumnsOrFormulas or #JoinColumns with #NamedEntityGraph(includeAllAttributes = true)
I tried to also left join the entity in Specification and it also cause n+1 query issue.
Entity:
#Data
#Entity
#Table(name = "book")
#NamedEntityGraph(name = "all", includeAllAttributes = true)
public class BookEntity implements JpaEntity {
#ManyToOne(targetEntity = CustomerEntity.class)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(column = #JoinColumn(name = "customer", referencedColumnName = "number", insertable = false, updatable = false)),
#JoinColumnOrFormula(column = #JoinColumn(name = "sub_customer", referencedColumnName = "sub_number", insertable = false, updatable = false)),
#JoinColumnOrFormula(formula = #JoinFormula(value = "'2019'", referencedColumnName = "year"))
})
private CustomerEntity customerEntity;
}
#Entity
#Data
#Table(name = "customer")
public class CustomerEntity implements JpaEntity {
#Id
#Column(name = "id")
private Integer id;
#Column(name = "number", columnDefinition = "INTEGER")
private Integer number;
#Column(name = "sub_number", columnDefinition = "INTEGER")
private Integer subNumber;
#Column(name = "year")
private String year;
}
Repository:
#Override
#EntityGraph(value = "all")
Page<BookEntity> findAll(Specification<BookEntity> spec, Pageable pageable);
I see that the query is correct. I see the join for the first query, so it looks like I have the full entity and no need to make n+1 query. But after correct query I see additional selects for the CustomerEntity.
Can someone help me to avoid n+1 issue with this case?

Categories

Resources