I have two tables - Table1 and Table2. Data structure of both the tables is same.
I have single VO for both Table1 and Table2. I have two .hbm.xml file for two tables separately -
Table1.hbm.xml and Table2.hbm.xml
In my java code, based on a condition I either need to save to Table1 or Table2
if(someCondition)
{
session.saveOrUpdate(VO); //This should be for Table1
}
else
{
session.saveOrUpdate(VO); //This should be for Table2
}
My problem is since that VO is same, there will be conflict in deciding which table to save.
Is it possible to have same VO mapped to two tables?
Note: The reason why I have such a requirement is Table1 and Table2 are in separate tablespace. One is partitioned and the other is not.
There are couple of other reasons for such a weird requirement which is beyond my control to change the architecture now.
In my opinion using two entity managers is a bit too much. What you need is to have a good abstraction around the table.
You can map the same class as many times you want you just have to map it under different name.
Than one good Repository pattern working with the abstract entity (instead of the concrete one) combined with a Factory or Builder to generate the two objects will get the job done. If you follow this approach you will not need to have this IF-ELSE flow.
#MappedSuperClass
class AbstractMappedSomeTimes {
private mappedAttribute;
}
#Table("yourtablename")
public class MappedOnce extends AbstractEntity{
}
#Table("yourtablename")
public class MappedTwise extends AbstractEntity{
}
Than you can have Repository working with AbstractMappedSomeTimes types of objects. You can also create a Factory that will generate either MappedOnce objects or MappedTwise objects.
Related
I'm creating a very simple application in Java that will be storing questions in an embedded Derby database. I've decided to use the DAO pattern for accessing the data in the database. I cannot make use of an ORM for this project.
A question will have data that I would normally model using a many to one relationship in a relational database. An example of this data would be:
A question will have one category. One category will have multiple questions.
A question will have a score of 1000, 2000 or 3000. A score will have many questions.
With the above in mind, I would create three tables (brackets indicate columns):
Question (id, question, scoreId, categoryId)
Score (id, score)
Category (id, category)
My first question is:
Would modelling my data across three tables like I suggest above be bad practice/the wrong way to go about this? Is there any benefit in storing score and category in separate tables? Or would it be better to combine them into the Question table? A many to one relationship that links to a table with a single column (with the exception of id) seems redundant to me, as instead of storing an id referencing the Score/Category table, we can simply store the value of the category/score (since the category/score table does not store any additional information).
My second question is:
If modelling my data across separate tables is the correct approach, then how would I access the data using the DAO pattern? My confusion comes from the following:
I would create a DAO to populate a Question model object that would look a little something like this:
public class Question {
String question;
String category;
Integer score;
}
I would create a concrete implementation of the DAO interface like this:
public class QuestionAccessObject implements QuestionDao {
private static final String TABLE_1 = "QUESTION";
private static final String TABLE_2 = "SCORE";
private static final String TABLE_3 = "CATEGORY";
#Override
public List<Question> getAllQuestions() {
List<Question> questions = new ArrayList<>();
//Run a query with joins across the three tables and iterate over the result to populate the list
return questions;
}
}
Shouldn't each DAO object only be concerned with a single table in the database? My approach listed above doesn't seem like the most correct way to go about this. Seperate tables would also make inserting data into the database very messy (I don't understand how I could take clean approach using the DAO pattern and multiple tables). Creating a DAO for the Score and Category tables just wouldn't really make sense.. (and if I did this, how would I populate my model?)
Would modelling my data across three tables like I suggest above be bad practice/the wrong way to go about this? Is there any benefit in storing score and category in separate tables....?
It's a matter of discussion. In case of score I rather stick this information with the question. On the other hand, the category would be in the separated table since more of the question would share the same category, so it makes a perfect sense.
Shouldn't each DAO object only be concerned with a single table in the database?
Yes, DAO, an object should be concerned with a single source of data - as you say. I would certainly try to avoid any ComplexDao since those classes tend to get more complex and the number of methods increases over the time.
There exist a service layer to combine those results together and provide an output to the controller using the very same service.
Modeling the data across separate tables is A correct approach (not necessarily the best).
Separating tables helps database normalization: https://en.wikipedia.org/wiki/Database_normalization.
One could argue that the DAO pattern implies that each DAO object is concerned with a single entity . Similar to how ORMs work, an entity could easily reference other entities.
When you query for a question you could also just return the category and score ids inside the question object and force the library user to fetch the score value and category value (lazy fetch) using those id values with their respective DAOs (score and category).
So I believe that what you're doing seems fine
Hope this helps
I have following tables:
master_table(id, col1, col2, discriminator_col)
join_table1(m_id, v_id)
value_table1(id, val)
join_table2(m_id, v_id)
value_table2(id, val)
there is single master table and several value tables joined to master table via join tables. Value tables contain single scalar value for each master_table row. Values from separate values tables are placed into descendant entities, so there are one MasterEntity and several Child1Entity, Child2Entity etc.
I would like not to create a separate entity for each value_table, just for each ChildEntity and somehow join value table to that entity.
MasterEntity:
#Entity
#Inheritance(...) // not sure what type of inheritance to use
public class MasterEntity {
#Id
private int id;
private String col1;
private String col2;
}
Child1Entity:
#Entity
public class Child1Entity extends MasterEntity {
// need to get value_table1.val column here
}
I could create entity for value_table and add many-to-one relation to Child1Entity, but if it is possible to avoid I would like to do that.
I tried to add two secondary tables (join_table1, value_table1) to Child1Entity, but I can not join join_table1 with value_table1, just with master_table.
If you want to use #Inheritance, you can't have those join_tables. With those join tables, your model says:
one value can belong to multiple master rows
one master row can belong to multiple value rows
If you just want: 1 master belongs to 1 value row, than use this:
master (id, ...)
value1 (masterId, ...)
value2 (masterId, ...)
With #Inheritance(strategy=InheritanceType.JOINED).
For more information have a look here: http://en.wikibooks.org/wiki/Java_Persistence/Inheritance
BUT: Whenever you use #Inheritance you will have to create a separate #Entity class for everything.
If you really need the 5 table layout from above, use #ManyToMany.
Basically JPA is made for Mapping Java Objects to SQL Tables, not the other way round ;) If you need to do thing's which aren't possible using JPA (or too complicated), you can always use JDBC and craft your queries and Entity mappings by hand.
I have a singleton that manages a list of some entities in my DB.
public class SchedulledQueue {
List<MyEntity> entities;
}
I need to store this list in my database. So I want a single table that only contains entities from which my singleton could grab all data.
TABLE schedulled_queue
(
entity_id character varying(32),
CONSTRAINT schedulled_queue FOREIGN KEY (entity_id)
REFERENCES tbl_my_entity (entity_id) MATCH SIMPLE
)
Is there any way to map my singleton SchedulledQueue in Hibernate to achieve this? Or should I not bother with such thing?
If you have multiple SchedulledQueue objects then it makes sense to have one to many relation between SchedulledQueue and MyEntity.
Since your SchedulledQueue in singleton. I don't see any advantage of creating an entity of it.
So, I don't found another way, except to create another Entity and use it through DAO.
public class SchedulledQueue {
List<SchedulledQueueEntity> entities;
}
SchedulledQueueEntity {
MyEntity ent;
}
Also it provided ability to use some additional fields for entity in queue, that we needed some time later.
I have many tables in my DB with exactly the same structure: same columns names and types.
The only difference between these tables is the their names (which I can only know in runtime).
I would like to create a mapping of a class to a table but giving the name of the table only during runtime (no static #Table annotation).
Is it possible?
Is there any other way to achieve my goal?
Directly - no. Because this is not a regular use-case. Normally you should not have dynamcally-generated tables. It is a valid use when you move some records to an archive table (or tables), but otherwise avoid it.
Anyway, you can make that work: make a native query, and map the result to your non-entity object. You will be able to select from any table and transform the result to an object. However, you can't insert or update that way.
Don't think associating or changing the table mapped to an entity dynamically is possible.
You can check #MappedSuperClass, which will allow you to define all fields in a class once and inherit them, so that there is no repetition and entities are empty class with mappings.
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1168
If you know the table name dynamically you can always instantiate the mapped class accordingly.
I'd like to explore Hibernate and used it in my project instead of JDBC.
My table design is highly normalized.
Suppose, I have this use case: Each insurance applied by a customer has one associated rateplan. Usually, in RDBMS this is implemented using two tables like below.
Table Insurance:
id long;
accountHolder varchar;
ratePlanId int; -->Rate Plan Id is Foreign Key to the RatePlanTable
Table RatePlan:
ratePlanId int;
ratePlanDesc varchar;
discountRate double;
Now, my question is..does this qualify as a onetomany relationship?
Most of the examples that I am seeing on the net regarding onetomany, involves some sort of collections (e.g An Order has a list of products). And when represented in class is translated below, which I think is really a one to many case?
public class Order{
private List products;
}
But how about my case? I don't think that it is a onetomany or I am just mislead by the examples?
How can I do a hbm mapping for my two classes? In my case, I would create two class to represent the two tables, but I am not sure how the hbm.xml would look like for the two class.
Yes, it is a one to many relationship, in that one rate plan is associated with many insurance policies. In entity traversal, when you would go from the Policy, you would get one Plan object, and conversely, from a Plan object, you would get a list of Policy objects.