I want to model my database tables as classes. In my database, I have many to many relationship as below, and I want to get ideas how to model it correctly.
.
These are the classes that I have tried to create for these three tables.
class Product {
......
private List<Price> priceList;
......
}
class Price{
.....
private List<Product> products;
.....
}
I think this way can help me model those tables correctly, but I lost the fields - price_list.amount.
If you want two classes, simply join the Price List table with either Price or Product. For example:
public class PricePoint
{
private int priceId;
private int priceListId;
private String description;
private Date createdOn;
private boolean status;
private int amount;
private List<Product> products;
}
public class Product
{
private List<PricePoint> pricePoints;
//...
}
Related
I have this entities:
public class AnswerEntity {
#ManyToOne
private UserEntity user;
#ManyToOne
private AnswerDirectoryEntity answer;
#ManyToOne
private QuestionEntity question;
}
public class QuestionEntity {
#ManyToOne
private QuestionnaireEntity questionnaire;
}
public class QuestionnaireEntity {
private String code;
}
I need to take all user answers by user ID and corresponding code from QuestionnaireEntity.
I do it by create query like this:
List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
and iterate over each object in my list and with using equals I compare each object to my questionnaire code:
for(AnswerEntity answerEntity : answerList){
if(answerEntity.getQuestion().getQuestionnaire().getCode().equals(questionnaireId)){
///
}
but this solution is very slow because it must iterate each object from my database,
can anybody tell my how to create an query in my repository which can help me?
You can use JPA method query this way in repository
List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);
I'm new to how the Room Database works particularly Querying and was wondering how one would go about querying the following.
Querying an object that contains an embedded object within it, based
on the embedded object.
Querying an object that contains a foreign key
#Entity
#Entity
public class Car {
#PrimaryKey()
private String id;
#Embedded()
private Engine engine
#Ignore
private List<Tire> tires
... //relevant getters and setters
}
public class Engine {
private String id;
private String type;
private String name;
}
#Entity(foreignKeys = {#ForeignKey(
entity = Car.class, parentColumn = "id", childColumn ="carIdFk")
}
public class Tire {
#PrimaryKey(autogenerated=true)
private int id;
private String model;
private String rimModel;
private String cardIdFk;
}
#Dao
public interface CarDao {
//Need a query to retrieve all cars where engine id == <somevalue>
//Need a query to retrieve all cars where tire model == <somevalue>
}
#Dao
public interface TyreDao {
//Need a query to retrieve all cars where tire id == <somevalue>
}
I am trying to establish the aggregation relationship between two Java classes through JPA annotations in order to persist them into a database.
public class Ticket
{
private String ticketNo;
private Date releasedDate;
private boolean printed;
}
public class Discount
{
private String percentage;
private Date releasedDate;
private boolean printed;
}
Such as mentioned here, the aggregation relationship is unidirectional and thus, only it is necessary to map one side. From the solution given by this page, I think the solution will be:
public class Discount
{
private String percentage;
private Date releasedDate;
private boolean printed;
#ManyToOne(name="TICKET_ID")
private Ticket ticket;
}
However, in some examples of aggregation, the many side class appears inside the one side class. Thus, I am considering this too:
public class Ticket
{
private String ticketNo;
private Date releasedDate;
private boolean printed;
#OneToMany(mappedBy="ticket")
private List<Discount> discounts = new ArrayList<Discount>();
}
Which option is the proper one?
This how you map a unidirectional many-to-one relationship:
#Entity
public class Ticket {
#Id
#GeneratedValue
private Long id;
private String ticketNo;
private Date releasedDate;
private boolean printed;
// getters and setters
}
#Entity
public class Discount {
#Id
#GeneratedValue
private Long id;
private String percentage;
private Date releasedDate;
private boolean printed;
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinColumn(name = "TICKET_ID") // you can rename the join column
private Ticket ticket;
// getters and setters
}
Note:
JoinColumn (foreign key in the database terminology) must be on the many side of the relationship (this is the Discount in your case).
The #Id annotations are also mandatory. In this case, the ID will be generated by the persistence provider automatically. If you are using database sequence or table or some other strategy you can redefine it.
That looks right to me. A discount has a ticket. You could also include the discounts accessible from the tickets like ticket.getDiscounts() if you need to access them in a query such as SELECT t FROM Ticket t WHERE t.discounts.percentage >= :discountPercentage.
#Entity
public class Ticket {
#Id
private String ticketNo;
private Date releasedDate;
private boolean printed;
#OneToMany(mappedBy = "ticket", fetch = FetchType.LAZY)
private List<Discounts> discounts;
}
#Entity
public class Discount {
private String percentage;
private Date releasedDate;
private boolean printed;
#ManytoOne(name="TICKET_ID")
private Ticket ticket;
}
However, I wouldn't recommend using #OneToMany as this can create problems serializing too much data to JSON if you are returning this as JSON results or just lazily loading too much data by accident. You should always be able to work with just #ManyToOne as an example if you did not put the #OneToMany association query can be SELECT t FROM Discount d INNER JOIN d.ticket t WHERE d.percentage >= :discountPercentage
I am searching for a design solution to the problem where I have 2 classes which depend on each other such that I have class Customer and class Order where:
Customer can have a list of orders (1-to-N) and an Order has a designated customer (1-to-1).
What is the best practice to break these kind of dependencies?
Assuming you have a dependency as follows:
public class Customer {
private long customerId;
private String name;
private String address1;
// ....
private List<Order> orders;
}
public class Order {
private long orderNumber;
private Date orderDate;
// ... others
private Customer customer;
}
You could create a third class to break the dependency:
public class CustomerOrder {
private final Customer customer;
private final List<Order> orders;
public CustomerOrder(Customer customer) {
super();
this.customer = customer;
this.orders = new ArrayList<Order>();
}
public void addOrder(Order order) {
orders.add(order);
}
public Customer getCustomer() {
return customer;
}
public List<Order> getOrders() {
return orders;
}
}
Now you can drop orders from the Customer class, and customer from the Order class. Or am I misunderstanding your issue?
As a software engineer for approx 2 years, the best I’ve seen for a case like that is to put a shadow definition of one class, without initializing it to anything, simply telling the compiler “hey orders exist”, then defining the other class explicitly, followed by your orders class explicitly. Does that get you in the right direction? Nodes and trees sometimes are modeled this way, and data structure and analysis of algorithms books tend to have decent design solutions to this too.
I have 3 classes as shown below.
#Entity
public class Family (
#Id
private String familyName;
private int size;
#OneToMany
protected VehiclesList getVehiclesList()
// getters and setters
)
public class VehiclesList (
private List<Vehicle> vehicles;
#Transient
private int totalInsuranceCost
// getters and setters
}
#Entity
public class Vehicle (
#Id
private String plateNumber;
private String model;
private String color;
// getters and setters
)
I want to create two tables. First one is "Family" with columns as "size", etc. This is easy enough. Second, I want to create a "Vehicle" table with reference to Family. This table should have the following columns:
plateNumber
FamilyName
model
color
I would like the Family class to reference the VehiclesList class, so that I can access information from the VehiclesList class. None of the data in the VehiclesList class will be persisted to the database - only the vehicles. How can I do this?
VehicleList is not an entity so you cannot use OneToMany on it.
totalInsuranceCost should not be a property like this but more something for a service method like
VehicleService.calculateTotalInsuranceCostForFamily (String familyName).
Your family entity then becomes:
#Entity
public class Family (
#Id
private String familyName;
private int size;
#OneToMany(mappedBy = "family")
private List<Vehicle> vehicles;
// getters and setters
)