I have 3 tables, each mapped to an entity. The entities are something like this:
#Entity
#Table(name = "person")
public class Person implements Serializable {
private int id;
//other fields
}
#Entity
#Table(name = "phone")
public class Phone implements Serializable {
private int id;
private Long price;
#ManyToOne
#JoinColumn(name = "personId")
private Person person;
#ManyToOne
#JoinColumn(name = "manufacturerId")
private Manufacturer manufacturer;
//other fields
}
#Entity
#Table(name = "manufacturer")
public class Manufacturer implements Serializable {
private int id;
private String name;
//other fields
}
What I want to do is to create a method that will return a list of Persons that have phones from a specified manufacturer with the price in a specified range.
EDIT: My dao class implements EntityJpaDao . I would need a solution that would work with this implementation.
Following query will return the Samsung mobile users with phone price range.
Criteria criteria = session.createCriteria(Phone.class, "phone");
criteria.createAlias("phone.person", "person")
criteria.add(Restrictions.between("phone.price", minPrice, maxPrice));
criteria.createAlias("phone.manufacturer","manufacturer");
criteria.add(Restrictions.eq("manufacturer.name", Samsung));
criteria.setProjection(Projections.property("person"));
List<Person> persons = criteria.list();
Related
I would like to get help with Criteria Query.
I want to get those students who has course in a specific room like 'math lab 1'.
Basically the java entity classes: ( + getters setters)
#Entity
public class Student {
private Long id;
private String name;
#OneToMany(mappedBy = "student")
private List<Course> courses = new ArrayList();
}
#Entity
public class Course {
private Long id;
private String name;
#ManyToOne
private Student student;
#ManyToOne
private Room room;
}
#Entity
public class Room {
private Long id;
private String name;
}
I would do a query like this:
SELECT DISCTINCT(s) FROM Student s
INNER JOIN Course c ON c.student = s
INNER JOIN Room r ON c.room = r
WHERE r.name = ?
I'm using a JPARepository called PublicationRepository and want to find all Publications from a certain Person. This Classes are connected over the Class Author.
Person Class:
#Entity
public class Person {
#Id
private String email;
private String telefon;
private String password;
#OneToMany(mappedBy = "person")
Set<Author> Author;
}
Author Class:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Author {
#Id
private int id;
#ManyToOne
#JoinColumn(name="Person_ID")
Person person;
#ManyToOne
#JoinColumn(name="Publication_ID")
Publication publication;
private String Date;
private String Writerstatus;
}
Publication Class
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Data
public class Publication {
#Id
private int id;
private String publicationname;
#OneToMany(mappedBy = "publication")
Set<Author> author;
}
And the PublicationRepository
public interface ProjektRepository extends JpaRepository<Projekt,Integer> {
}
public interface PublicationRepository extends JpaRepository<Publication,Integer> {
#Query(value = "SELECT pub.* FROM author as auth INNER JOIN publications as pub ON auth.publication_id = pub.id WHERE auth.person_id = ?1", native = true)
List<Publication> findAllPublicationsOfThisPerson(int personId);
}
Try this.
I would also recommend to annotate the entities with their table names:
#Table(name = "publication")
You use a manually build table for a Many-to-Many relationship Author
You could also delegate that to Spring Data Jpa by using #ManyToMany Annotation.
A good tutorial:
https://attacomsian.com/blog/spring-data-jpa-many-to-many-mapping
I am new to hibernate just stuck in map annotation in hibernate
CASE 1) #MapKey
When you use a Map you always need to associate at least two entities. Let's say we have
an Owner entity that relates to the Car entity (Car has a FK to Owner). So, the Owner will have a Map of Car(s):The #MapKey will give you the Car's property used to group a Car to its Owner. For instance, if we have a vin (Vehicle Identification Number) property in Car, we could use it as the carMap key:
#Entity
public class Owner {
#Id
private long id;
#OneToMany(mappedBy="owner")
#MapKey(name = "vin")
private Map<String, Car> carMap;
}
#Entity
public class Car {
#Id
private long id;
#ManyToOne
private Owner owner;
private String vin;
}
CASE 2) #MapKeyEnumerated
The #MapKeyEnumerated will use an Enum from Car, like WheelDrive:
#Entity
public class Owner {
#Id
private long id;
#OneToMany(mappedBy="owner")
#MapKeyEnumerated(EnumType.STRING)
private Map<WheelDrive, Car> carMap;
}
#Entity
public class Car {
#Id
private long id;
#ManyToOne
private Owner owner;
#Column(name = "wheelDrive")
#Enumerated(EnumType.STRING)
private WheelDrive wheelDrive;
}
public enum WheelDrive {
2WD,
4WD;
}
CASE 3) #MapKeyTemporal
The #MapKeyTemporal will use a Date/Calendar field for grouping, like createdOn.
#Entity
public class Owner {
#Id
private long id;
#OneToMany(mappedBy="owner")
#MapKeyTemporal(TemporalType.TIMESTAMP)
private Map<Date, Car> carMap;
}
#Entity
public class Car {
#Id
private long id;
#ManyToOne
private Owner owner;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_on")
private Calendar createdOn;
}
Case 4) #MapKeyJoinColumn
The #MapKeyJoinColumn requires a third entity, like Manufacturer so that you have an association from Owner to Car and car has also an association to a Manufacturer, so that you can group all Owner's Cars by Manufacturer:
#Entity
public class Owner {
#Id
private long id;
#OneToMany(mappedBy="owner")
#MapKeyJoinColumn(name="manufacturer_id")
private Map<Manufacturer, Car> carMap;
}
#Entity
public class Car {
#Id
private long id;
#ManyToOne
private Owner owner;
#ManyToOne
#JoinColumn(name = "manufacturer_id")
private Manufacturer manufacturer;
}
#Entity
public class Manufacturer {
#Id
private long id;
private String name;
}
The mapping to a java.util.Map doesn't have any impact on the table mapping. In all cases, you are mapping a Many-to-One/One-to-Many associations. In your table model, this gets represented by 2 database tables. The only exception is the 4th case, where you have another entity and table but that's not part of the actual association mapping.
I explain this mapping in great details on my blog in How to map an association as a java.util.Map
To sum it up:
Case 1-3 get mapped to 2 database tables: Owner and Car.
Case 4 gets mapped to 3 database tables: Owner, Car and Manufacturer.
I am trying to add multi-language to the description and title fields of one of my Entities but without success. My Entity is like below and my database is MySQL:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "project")
public class ProjectEntity implements Serializable {
#Id
#Column(name="id")
private Integer id;
#Column(name="team_size")
private Integer teamSize;
#Column(name="description")
private String description;
#Column(name="title")
private String title;
#OneToMany
private List<DetailsEntity> details;
}
I alreaady tried to add a projectDetails entity that contains the description and title, but as I need multilanguage, the Project will now have a list of ProjectDetails in my backend, what I don't need.
Here is what the projectDetails could looks like:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "project_details")
public class ProjectDetails implements Serializable {
#Id
#Column(name="id")
private Integer id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="language")
private String language;
#Column(name="project_id")
private Integer projectId;
}
I would like to be able to do something with the JPA repository requests, like this:
#Repository
public interface ProjectEntityRepository extends JpaRepository<ProjectEntity, Integer> {
#Query("select p from ProjectEntity p left outer join ProjectDetails d on p.id=d.project_id and d.language=:language")
List<ProjectEntity> findAllForLanguage(String language);
}
Any idea on how to change part of this to return the Project entity with values of only 1 ProjectDetails?
Thank you
I have two tables called Stock and stock_daily_record. Please find the table structure below
Stock
Id (primary key) Int
Name varchar
stock_daily_record
Stockid(primary key & foreign key on id of Stock)
Stock_price (Primary key)
My Entity class
#Entity #Table(name = "stock")
class Stock
{
#id #column(name=”id”)
Private int id;
#column(name=”name”)
Private String name;
#oneToMany(fetch = FetchType.LAZY)
Private Set<DailyStockRecord> dailyRecords;
//Getters and setters,equals
}
My next class DailyStockRecord contains composite key alone. How to define mapping between this two classes. Plus how to define DailyStockRecord entity?
Note:
Please don't consider my Database design cos I tried to project my actual problem through this dummy design
#Entity #Table(name = "stock_daily_record")
class StockDailyRecord
{
#id #column(name=”Stockid”)
Private int stockId;
#column(name=”Stock_price”)
Private String stockPrice;
#ManyToOne(fetch = FetchType.LAZY)
#joinColumn(name="id")
Private Stock stock;
//Getters and setters,equals
}
Try this configuration
#Entity
#Table("stock_daily_record")
public class DailyStockRecord
#EmbeddedId
private DailyStockId stockId;
#MapsId("stockId")
#ManyToOne
private Stock stock;
And the embeddable key as follows:
#Embeddedable
public class DailyStockId
private int dailyStockId;
private int stockId;
And update your code to
#Entity
#Table(name = "stock")
public class Stock
#id #column(name=”id”)
Private int id;
#column(name=”name”)
Private String name;
#OneToMany(fetch = FetchType.LAZY, mappedBy="stock" )
Private Set<DailyStockRecord> dailyRecords;
//Getters and setters,equals
}