I am a beginner in JPA. As per requirement I am trying to fetch data from multiple tables (Feeder,Monthlyfeederdetails) and insert into another table (Report). Can someone please show me the way to do it. I have looked at a few sql examples like
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
but how do I reference the different tables in one repository?
I need to get the feeder_name, feeder_type from Feeder table
and duration_of_intr,no_of_afcon from Monthlyfeederdetails table
and also the the (duration_of_intr * no_of_afcon)
in the third table i.e Report table
Feeder Model
#Entity
public class Feeder {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int feeder_id;
private String feeder_name;
private int feeder_type;
private int no_of_consumer_in_the_feeder;
}
Getters and setters
Monthlyfeederdetails Model
#Entity
public class Monthlyfeederdetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private int user_id;
private int feeder_id;
private int feeder_type;
//private int no_of_con_in_feeder;
private int duration_of_intr; //duration of interruption
private int freq_of_intr; //frequency of interruption;
private int no_of_afcon; //no of consumer affected due to shutdown
private int month;
private int year;
}
Get and Set
Report Model
#Entity
#Table(name= "report of caifi and caidi")
public class Report {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int reportid;
private String feeder_name;
private int feeder_type;
private int no_of_afcon;
private int duration_of_intr;
private int no_of_afconXduration_of_intr;
How can i achieve that?
Related
I have a two table as table as
#Entity
#Table(name = "product", uniqueConstraints=#UniqueConstraint(columnNames={"product_idn"}))
public class Product implements Serializable {
private static final long serialVersionUID = 21409635044L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String product_idn;
}
another table as
#Entity
#Table(name = "storage")
public class Storage implements Serializable {
private static final long serialVersionUID = -67165579239L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", nullable = false)
#JsonBackReference
private Product product;
}
Now I am fetching record from storage table. Should create a index (Non-Unique)on product_id of storage table? I have to fetch storages count per on product/ featching storages based on product.
Just add #Index annoation like below and it should work fine.
#Entity
#Table(name = "storage", indexes = #Index(columnList = "product_id",name = "storage_productId_index"))
public class Storage implements Serializable
The JPA query below gives me perfect IDs that I want but I need the rest of the fields of that row.
I wonder if there is a another way to create this query where I can get all fields for these selected IDs.
#Repository
public interface UserResponseRepository extends JpaRepository<UserResponses, Integer> {
#Query("SELECT DISTINCT r.users.userId,r.assessments.vassId FROM UserResponses r")
List<Integer> findByAssessmentsUsers();
Table 1
public class UserResponses implements Serializable {
#Id
#GeneratedValue
private Integer UrId;
...
#ManyToOne
private Users users;
#ManyToOne
private Assessments assessments;
Table 2
public class Users implements Serializable {
#Id
#GeneratedValue
private Integer userId;
...
#OneToMany
private List<Assessments> assSet;
#OneToMany
private Set<UserResponses> userRes;
Table 3
public class Assessments implements Serializable {
#Id
#GeneratedValue
private Integer vassId;
#ManyToOne
private Users users;
#OneToMany
private Set<UserResponses> userResSet;
As far as I understand you need group by statement in your query instead of distinct
#Query("SELECT r.users.userId, r.assessments.vassId FROM UserResponses r group by r.users.userId, r.assessments.vassId")
List<Object[]> findByAssessmentsUsers();
But here query returns List<Object[]>. I'd recommend using List<AssessmentsDto> as query result.
public class AssessmentsDto {
public AssessmentsDto(Integer userId, Integer vassId) {
this.userId = userId;
this.vassId = vassId;
}
Integer userId;
Integer vassId;
public Integer getUserId() {
return userId;
}
public Integer getVassId() {
return vassId;
}
}
Dto usage:
#Query("SELECT new yourProject.dto.AssessmentsDto(r.users.userId, r.assessments.vassId) FROM UserResponses r group by r.users.userId, r.assessments.vassId")
List<AssessmentsDto> findByAssessmentsUsers();
I am working on below database tables :
users table - Each row represents a User in the system. It has a foreign key constraint to countries table.
countries table - Each row represents a Country and each country can have a list of dialects stored in table dialects.
I am using Spring data JPA and have created below entity classes
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "full_name")
private String fullName;
#Column(name = "createdAt")
private Date createdAt;
#Column(name = "country_code")
private Integer countryCode;
#Column(name = "dialect_key")
private String dialectKey;
}
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer country_code;
#Column(name = "name")
private String name;
#Column(name = "continent_name")
private String continentName;
#ElementCollection
#CollectionTable(name = "Dialect", joinColumns = { #JoinColumn(name = "country_code") })
private List<Dialect> dialectList;
}
#Embeddable
public class Dialect {
private String name;
}
Now I have a use case where I need to fetch the full name and dialect name for a given User.
Select u.full_name, d.name from users u
join countries c on u.country_code = c.country_code
join dialects d on c.country_code = d.country_code
where u.id = :user_id and u.dialect_key = d.dialect_key
Question - The above query works fine when ran as a native query and returns a List of Object. Further I am mapping the Objects List to the List of POJO. Is there a better way to do this to avoid Object -> POJO conversion explicitly ?
I am creating two tables using Spring boot and JPA:
Apartment table:
id, name, address_id, website
Address table:
id, street_num, street, city, .....
the address_id should be the foreign key and pointing to id in address table.
I couldn't get my code working. Here are my two Entity classes:
Apartment.java:
#Entity
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinTable(name = "address",
joinColumns = #JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
Address.java:
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer apt_id;
private String streetNum;
private String street;
private String city;
private String state;
private String zipCode;
//getters and setters
what I am getting is an extra column called address_id in address table....and missing address_id in apartment table....
Many Thanks!
Hibernate one to one mapping with foreign key association
In this kind of association, a foreign key column is created in owner entity
The join column is declared with the #JoinColumn annotation which looks like the #Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
Replace Your Apartment Class with this:
#Entity
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
I have this activity_company table which includes an activity and company. I am trying to order the result of this query by modified_date and id. And in the activity table there is a boolean field such as shared. All the shared values are false in the database but after this query the resulted objects' shared fields are displayed as true even if they are still false in the DB. Any idea what causes this situation ?
SELECT activity.*
FROM activity
INNER JOIN activity_company ON activity.id=activity_company.activity_id
WHERE activity_company.company_id=1
ORDER BY activity.modified_date, activity.id
This is the activity class;
#Entity
public class Activity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(columnDefinition = "TEXT")
private String param;
private Date createdDate;
private int activityType;
private long classNameId;
private long classPK;
private Date modifiedDate;
private boolean shared;
#ManyToOne
private User creatorUser;
#ManyToOne
private Company creatorCompany;
#OneToMany(mappedBy = "activity")
private List<ActivityCompany> activityCompanies = new ArrayList<ActivityCompany>();
#OneToMany(mappedBy = "activity")
private List<ActivityAttachment> activityAttachments;
public Activity(String param, User user, int activityType) {
this.param = param;
this.createdDate = new Date();
this.activityType = activityType;
this.creatorUser = user;
this.modifiedDate = new Date();
}
and activitycompany;
#Entity
public class ActivityCompany {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Activity activity;
#ManyToOne
private Company company;
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Long getId() {
return id;
}
}