Hibernate is not getting Inherited attributes in parent class of pojo - java

I have some common fields in every table of Database
added_on and added_by
I created a pojo class:
public class CommonBean{
#Column(name="added_on")
public Date addedOn;
#Column(name="added_by")
public Integer addedBy;
//setters and getters
}
And all the pojo classes are extends that pojo class:
example:
#Table(name = "employee")
#Entity
public class HrEmployee extends CommonBean implements java.io.Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
#Column(name="first_name")
private String firstName;
#Column(name="middle_name")
private String middleName;
#Column(name="last_name")
private String lastName;
}
But When I am calling list method of hibernate criteria.
I can see the generated query in the console:
Hibernate:
/* criteria query */ select
this_.id as y0_,
this_.first_name as y2_,
this_.middle_name as y3_,
this_.last_name as y4_
from
hr_employee this_
Why it is not getting attributes from its parent class?
I am not sure whether it is possible or I am making mistake somewhere.
Thanks

Annotate CommonBean class with #MappedSuperclass annotation

You need to Annotate Super class with #MappedSuperclass. this is how you say hibernate to inherit properties from super class
this will help you

Related

Hibernate: How to map a class that "has-a" subclass to a single table?

I have a class BacktestResult that contains a property BacktestInputs. I want hibernate to create a single table that contains the contents of both. Here's what I have so far:
#Entity
#Table(name="backtest_result")
public class BacktestResult {
#Id
Long backtest_id;
public int userId;
BacktestInputs inputs;
#OneToMany
#OrderColumn(name="backtest_id")
public BacktestChartDataPoint[] series;
//getters and setters
The BacktestChartDataPoint class looks like this:
#Entity
#Table(name="backtestchart_datapoint")
public class BacktestChartDataPoint {
#Id
public Long id;
public Long backtest_id;
#ManyToOne
#JoinColumn(name="backtest_id", nullable=false, insertable=false, updatable=false)
private BacktestResult backtestResult;
The BacktestInputs class looks like this:
public class BacktestInputs {
public String strategy_name;
public String version;
etc...
As long as I comment out the BacktestInputs in BacktestResult, hibernate correctly creates 3 tables:
backtest_result
backtest_result_series
backtestchart_datapoint
But I want the contents of BacktestInputs to be included in the BacktestResult table. If I uncomment it, get error:
Could not determine type for:
net.tekknow.moneymachine.model.BacktestInputs, at table:
backtest_result, for columns: [org.hibernate.mapping.Column(inputs)]
What is the proper way to handle class hierarchy with "has-a" relationships, NOT "is-a" relationships?
You need to annotate the class BacktestInputs with #Embeddable
(see https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#embeddables)

Relationship mapping in Hibernate

I have a two table Company and CompanyRepo like below
COMAPNY
COMPANY_REPO
I have entities for those two tables like this :
#Entity
#Table(name="COMAPNY")
public class Company implements Serializable {
#Id
#Column(name="COMPANY_ID")
private Long companyId;
#Column
private String companyName;
#OneToMany(mappedBy="COMPANY")
private List<CompanyRepo> companyRepo;
}
#Entity
#Table(name="COMAPNY_REPO")
public class CompanyRepo implements Serializable {
#Id
#Column(name="COMPANY_REPO_ID")
private Long companyRepoId;
#Column
private String COMPANY_ID;
#Column
private String DEPT_ID;
#ManyToOne
#JoinColumn(name="COMPANY_ID")
private Company company;
}
Now i want to execute below query using a Hibernate relationship mapping
select Company_name from company as C ,company_repo as cr where c.company_id=cr.company_id and dept_id=10
I wrote a JPA repository like below by using a #OneToMany in Company table and #ManyToOne in CompanyRepo. But in resultant I am getting multiple COMPANYobject inside COMPANY_REPO Object.Does my relationship mapping is correct ?
public interface CompanyRepository extends JpaRepository<CompanyRepo, Long> {
public CompanyRepo findByDeptId(Long deptId);
}
Given your current database design, try something such as the following:
public interface CompanyRepository extends JpaRepository<Company, Long> {
#Query(value="SELECT * from company as C WHERE c.company_id = (SELECT cr.company_id FROM company_repo as cr WHERE cr.dept_id = ?1)", nativeQuery=true)
public Company findByDeptId(Long deptId);
}
The #Query annotation is a very powerful and flexible way to define methods in Repository interface. If you need more complex logic, I would recommend reading about the use and possibilities of the annotation. See here.
Based on your entity class your have multiple
COMPANY_ID that is not a proper way to declare your column name.
#Column
private String COMPANY_ID;
#ManyToOne
#JoinColumn(name="COMPANY_ID")
private Company company;
So please change your #Column
private String COMPANY_ID; to #Column("comp_id)
private String companyId;
If you want to get the CompanyRepo based on Company type then you need to change your query to fetch the dept id.
And your #Column
private String DEPT_ID; is String datatype so pass String to your repository.
#Query(" select companyRepo.company from CompanyRepo as companyRepo where companyRepo.DEPT_ID = :deptId")
public Company findByDeptId(String deptId);

How to query jpa entity in JOINED inheritance, without creating table for same?

I am trying to implemet inheritance hierarchy as mentioned in below image using hibernate Joined strategy.
Since Joined strategy creates table for entity regardless of entity class is Concrete or Abstract.
I don't want to create separate table for "CompanyEmployee" so I declared it as mapped superclass, but I should able to query this class/subclasses in polymorphic way.
Since it is mapped superclass I can't do this, and if I declare it to be entity it will create table which I want to avoid.
So, is there any way I can achieve this? I am thinking about mixed inheritance but from below quote it doesn't seems to be a good solution.
Mixed Inheritance
We should begin this section by saying that the practice of mixing inheritance types within a single
inheritance hierarchy is currently outside the specification. We are including it because it is both useful
and interesting, but we are offering a warning that it might not be portable to rely on such behavior,
even if your vendor supports it.
Inheritance hierarchy
#Entity
#Table(name="j_employee")
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="emp_type", discriminatorType=DiscriminatorType.STRING)
public abstract class JEmployee extends AuditLog implements Serializable {
#Id
#Basic
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="employee_id")
private Integer employeeId;
#Basic
#Temporal(TemporalType.DATE)
#Column(name="join_date")
private Date joinDate;
#OneToOne
#JoinColumn(name="person_id", nullable=false)
private Person person;
#Column(name="emp_type", updatable=false, insertable=false)
private String empType;
//Getters and Setters
}
#Entity
#Table(name="j_contract_employee")
#DiscriminatorValue(value="JContractEmployee")
#PrimaryKeyJoinColumn(name="contract_employee_id", referencedColumnName="employee_id")
public class JContractEmployee extends JEmployee implements Serializable {
#Basic
#Column(name="daily_rate")
private Integer dailyRate;
#Basic
#Column(name="term")
private Integer term;
//Getters and Setters
}
//Don't want to create table for this class, but I should able to query this clas/subclasses in polymorphic way
#MappedSuperclass
public abstract class JCompanyEmployee extends JEmployee implements Serializable {
#Basic
#Column(name="vacation")
private Integer vacation;
//Getters and Setters
public Integer getVacation() {
return vacation;
}
public void setVacation(Integer vacation) {
this.vacation = vacation;
}
}
#Entity
#Table(name="j_part_time_employee")
#Access(AccessType.FIELD)
#DiscriminatorValue(value="JPartTimeEmployee")
#PrimaryKeyJoinColumn(name="part_time_employee_id", referencedColumnName="employee_id")
public class JPartTimeEmployee extends JCompanyEmployee implements Serializable {
#Basic
#Column(name="hourly_rate")
private Integer hourlyRate;
//Getters and Setters
}
#Entity
#Table(name="j_full_time_employee")
#Access(AccessType.FIELD)
#DiscriminatorValue(value="JFullTimeEmployee")
public class JFullTimeEmployee extends JCompanyEmployee implements Serializable {
#Basic
#Column(name="salary")
private Integer salary;
#Basic
#Column(name="penion")
private Integer pension;
//Getters and Setter
}

Hibernate - Use of #OneToMany or #ManyToMany targeting an unmapped class: com.podro.model.Journey.roadWay[com.podro.model.RoadElement]

I saw similar questions, but answers weren't helpful. So, i get this error:
Use of #OneToMany or #ManyToMany targeting an unmapped class: com.podro.model.Journey.roadWay[com.podro.model.RoadElement]
I'm trying to create List with objects of RoadElements (which is interface for class Point and Section). There is any other way to do it? From what i know, i guess that is the only way to create proper mapping for this classes, and have list of this elements.
#Entity
#Table(name="Journey")
public class Journey {
// Some other fields
#Column(name="road_way")
#ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<RoadElement> roadWay;
}
#MappedSuperclass
public interface RoadElement {}
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#Table(name="Point")
public class Point implements RoadElement{
#Id
#Column(name="id")
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
private String name;
#Column(name="time_in_days")
private int timeInDays;
private Rate rating;
}
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#Table(name="Section")
public class Section implements RoadElement{
#Id
#Column(name="id")
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name="section_name" , length=100)
private String sectionName;
#Column(name="time_in_days")
private int timeInDays;
#Column(name="kind_of_transport")
private Locomotion kindOfTransport;
}
Thanks for answers, I would be very grateful for help!
Associations are between entities. RoadElement is not an entity. It's an interface.
You may not do what you're trying to do. Hibernate needs to know the type of the entities contained in roadWay.
So, RoadElement should be a class, annotated with #Entity, having an ID that uniquely identifies a RoadElement among all the road elements (sections, points, etc.)
Section and Point should extend from RoadElement, and should NOT have their own ID, since it's inherited from RoadElement.

inheritance relationship No identifier specified for entity

class A implements Serializable{
private static final long serialVersionUID = 1L;
#Id
Integer id;
...
// constructor getter and setter
}
#Entity
class B extends A{
private static final long serialVersionUID = 1L;
#Column
String name;
#Column
String age;
...
//constructors, getters and setters
}
As you see above, class A extends from class B, B should have the identifier id inheritance from A. but i got the No identifier specified for entity: com.d.e.B
what did i missed? thanks in advance.
You missed the #MappedSuperclass annotation on A, to tell Hibernate/JPA that properties and JPA annotations found in A must be considered.
In this example, #MapperSuperclass will work.
If you have entity relationships (one to many, many to one, etc...) the A class should be defined as an entity and the #Inheritance annotation should be used instead.
I had the same error ("No identifier specified for entity") because my A class had the #Inheritance annotation but not the #Entity annotation

Categories