How to use different tables for entity on runtime using JPA? - java

I am building a COTs product which records sales data. Since it will be used by different business owners i want to save the sales data to the owner specific tables. So how do i use a single entity to perform operation on different tables based on unique owner id? My core object and business logic is the same. I am just stuck on how to persist data for each owner in a separate tables. I don't want to have it all in one table with owner id as unique. It just creates risk of impacting all the clients data while any update/migration to the table.

Related

How to bind entity to different tables with SpringJPA/SpringBoot

I want to design a system. There are different customers using this system. I need to create the duplicated tables for every customer. For example, I have a table Order, then all of order records for customerA are in table Order_A, as well as customerB data are in table Order_B. I can distinct different customers from session, but how can I let Spring JPA to reflect the RDS table data to Java object?
I know 2 solutions, but both are not satisfied.
Consider to use Mybatis because it supports load SQL from xml file and parameters inside SQL;
Consider to use org.hibernate.EmptyInterceptor. This is my current implement in my project. For every entity, I must define a subclass of it. It can update the SQL before Hibernate's execution.
However, both are not graceful. I prefer the better solution.

Cassandra - Distributed Row Locking for Select AND Update

I have a micro-service which runs on multiple machines in two regions which connects to Cassandra DB. I have the following table structure.
CREATE TABLE gifts (
gift_id text,
user_id text
PRIMARY KEY gift_id
);
The table contains a list of gift id.
During multiple concurrent request each user must be assigned a unique gift i.e select a random gift_id and update the user_id.
Will LWT be helpful to solve this problem?
Limitations:
Cannot use zookeeper for locking
Cannot use any relational database.
Note that LWT doesn't affect SELECTs. The usual last-writer-wins and tunable consistency semantics apply (though running a SELECT with consistency level ALL guarantees that you'll see the write from the latest INSERT/UPDATE (which in Cassandra should best be considered the same: INSERT has upsert semantics)).
You can use LWTs to ensure that no two users share a gift_id. Simply INSERT with IF NOT EXISTS if once a gift is associated with a user it can't be associated with any other user. Alternatively, you can do a SELECT user_id FROM gifts WHERE gift_id = ... and then INSERT with IF user_id = the_user_id_from_the_select.

How to implement one-to-many relationships with DynamoDB

everyone! I have two tables that I would like to join via DynamoDb, but since the latter is not a relational db, I don't know how to map the link between the two tables.
In particular, I have a Price List table and a Detail List table that contains the details of the first one. How can I implement one-to-many relationship in java using dynamoDB with Spring Boot?
DynamoDB is basically a key-value store. You only every perform a lookup based on a key. That key may be artificial, not just a user id, but maybe "user_id#product#order" but still it will be a key-based lookup. If you want to use DynamoDB you have to store the data in a way that all queries that you will need will all boil down to basic key-based access (plus some sorting).
You have to do the exact opposite of normalizing your data and splitting relations into multiple tables: you have to de-normalize all your data to store the data and all the relations just in one table, multiple times, with multiple complex artificial keys. See e.g. https://www.youtube.com/watch?v=HaEPXoXVf2k on how to use LSIs, GSIs, how to model your data, how to choose artificial keys, etc.
That means you will not have Item, Order and OrderItem table that you join together, but you will have just one Everything table which may have the fields: userid, username, ordernumber, itemid, itemprice, itemquantity, itemname, orderdate, shippingaddress, etc.
And if you have three items in an order you will have three entries in this table. That means the username will be in the table very often, that means the itemname will be in the table very often and changing them will be difficult but that is how things are if you want to use dynamodb.
That is how you model one-to-many relations, by packing them into a single table and add proper indexes.
If you do have no idea about the current or future access patterns of your data or how to structure your data properly then dynamodb is the wrong tool for you.
The question you are asking gets at the very essence of working with DynamoDB and NoSQL data modeling. It is not as simple as applying your relational database knowledge to DynamoDB. Take a moment to familiarize yourself with the DynamoDB basics before you get too far into solving this problem.
Watch this video about modeling one-to-many relationships in DynamoDB. I would recommend you watch the entire video from the beginning, as it's one of the best introductions to the topic currently available.

mySQL Java Database Modeling

In trying to create a SQL database that can be queried within java, but I'm not sure how to structure it. Here are my categories:
1. State
2. Cites within each state
3. Venues within each city
4. Specifics about each venue
This might seem simple to some, but I am concerned with the amount of information that will be located in category #4, since that category alone could house the most data. The most important part of this is that I would of course need to query this information in category #4 and return the information. Is it common practice to have a category with a lot of information in it or do I need to break down category #4 even further? Also, another issue I am coming across is that I am using java to create arrays or arrayLists for all this info and I don't know how to get the data from the arrays to mysql. Any info is appreciated.
Creating relational tables for a relational database and querying relational tables in a relational database using Java are two different tasks.
First, let's create the relational tables.
State
-----
State ID
State Name
...
In the State table, you store all the information about a state. The State ID is the primary (clustering) key, and is an auto-incrementing integer.
City
----
City ID
State ID
City Name
...
In the City table, you store all the information about a city. The State ID is a foreign key to the State table. In the few cases where a city is in multiple states, you create a city row for each state. As an example, Bristol, Virginia and Bristol, Tennessee is a city in two states.
Venue
-----
Venue ID
City ID
Venue Name
Venue Type
Venue Address
...
Venue Type
----------
Venue Type ID
Venue Type Description
In the Venue table, you store all the information about a venue. The City ID is a foreign key to the city. You can get the state information from the city row.
In the Venue Type table, you store the various venue types, like hotel, theater, restaurant, retail store, etc.
The only reason you would create a Specifics table is if there are multiple types of specifics for a venue. Otherwise, you can add a Venue Description column to the Venue table.
First, get your relations for your relational tables correct. Then, you can see how to map the relations to Java classes. Classes consisting of lists are probably the correct approach.
Get your code to work with the most direct mapping between your domain objects and your tables. If down the line you realize you're storing too much data in one table, you'll be able to refactor by breaking that data more. But I wouldn't worry too much about having too much data in a table, that's what databases are made for. What you need to think about is how you're going to access that data, and make sure you have proper indexes and primary keys on it.
To insert several rows of data from Java to mysql, search the Web. Java: Insert multiple rows into MySQL with PreparedStatement may be a good start.

Duplicate inserts when using QueryHints.BATCH

I'm developing a Java desktop application (SE, JDK 1.6.0) connecting directly to a remote MySQL Server (5.0) via EclipseLink 2.3.0, using a Swing GUI.
The application where my problem occurs looks like this: the user issues a search for companies (e.g. all companies located in X) and the results are loaded in a JTable. When a user selects a company much additional data from other related tables is shown (e.g. notes about the company, employees, phone number of employees etc.), most of them are #OneToMany relations.
Because of the amount of data and tables needed for each entry I have to optimize my search query to use joins and batch fetch:
import org.eclipse.persistence.config.QueryHints;
import javax.persistence.Query;
Query query = entityManager.createQuery("SELECT DISTINCT c FROM Company c WHERE c.y = x");
query.setHint(QueryHints.LEFT_FETCH, "c.companyWebsiteCollection");
query.setHint(​QueryHints.BATCH, "c.person2companyRelationCollection");
List list = query.getResultList();
The problems occur with person2companyRelationCollection which holds relations to persons who have relations to other companies which have connections to other persons and companies etc.
When I select company1 in jTable1 and all related persons are shown in table2, an INSERT query is issued that tries to insert the shown person2CompanyRelation entity again into the DB, causing a om.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry.
What am I doing wrong with my query hints?
Additional information:
I don't detach any objects
I don't merge any objects
all entities are managed by the same EntityManager
all is done within the same transaction
the PK of Person2companyRelation is a composite primary key (#EmbeddedId) containing
companyId
personId
relationTypeId
the problem doesn't occur when only using with query.setHint(​QueryHints.LEFT_FETCH)
Correction: the problem does occur when batch-fetching any object using QueryHints.BATCH, regardless of the key type
Are you detaching objects, mixing objects from different queries/transaction/entity managers, are you using merge?
Does the insert occur without using batch fetch?
How is the Id of the object and the relationship mapped?

Categories