I have two tables, which have a one-to-one relationship and look something like this:
OrderItem
ID data1 data2 data3
1 a b c
2 d e f
3 g h i
DisputedItem
ID data4
1 q
3 r
Is there a way to pull data4 into my Hibernate model for OrderItem without having a separate DisputedItemModel? Preferably using annotations.
You can use Hibernate #Formula annotation, if you have annotation based mappings or <formula> tag if you are mapping by XML.
What formula can do is help you extract a value by a query and map it to a field in your OrderItem domain model. This field can be from any table but the query thats used to map the property should return the indented field type.
You can use following URL for reference Hibernate Formula
Yes, here is an example:
#Table(name = "table")
public class c
{
#Id
#Column(name = "ID")
private int Id;
#Formula("(select t.data from table t where t.ID = ID))")
private String data;
}
Related
I have a native query in spring boot like this:
select
a.x,
a.y,
b.m,
b.n
from
table1 a,
table2 b
where
a.x = b.x
order by a.x
here for each entry for table1 there can be multiple matching rows in table2. I.e there is OneToMany mapping.
for this i created an object to hold the data:
#Entity
#Table(name="table1")
#SecondaryTable(name = "table2", pkJoinColumns = {#PrimaryKeyJoinColumn(name = "x", referencedColumnName = "x")})
public class TableData {
#Id
#Column(name = "x")
public String x;
#Column(name = "y")
public String y;
#Column(name = "m", table = "table2")
public String m;
#Column(name = "n", table = "table2")
public String n;
//getters and setters
When i execute the sql in my db i see the results coming fine. I.e i see two different rows with same a.x but with different b.m and b.n
But my json response has two identical rows with same a.x and same b.m and b.n
Sample data:
table1:
ManagerID|ManagerName|Role
'1','John','Manager'
table2:
ManagerID|AssociateName|AssociateId
'1','Peter','2'
'1','Jacob','3'
Expected output
'1','John','Peter','2'
'1','John','Jacob','3'
Output i am seeing right now:
'1','John','Peter','2'
'1','John','Peter','2'
Any guess where i am getting wrong ??
My problem got resolved by using the #IdClass annotation as the resulting data from the query was a join and the uniqueness can be maintained by a combination of fields !!
I want to join table A with table B in Spring Boot.
Table A has multiple rows but table B has only one row (with general parameters, by the way)
There is no joining columns between these two tables
I just want to use a column from table B in entity class of table A
Table A
#Getter
#Setter
#Entity
#Table(name="tableA")
public class tableA {
#Id
#Column(name = "id")
private Long id;
#Column(name = "code")
private String code;
}
TableB has only one row with one column "codeformatt"
| codeformat |
|------------|
| AAAAA-AAAA |
this is the format for the code of tableA. I want to use it yo display code with the proper format.
There are no foreign keys or joining columns
If I had to write it in SQL I would write it like this:
select A.code , B.codeformat
from tableA A inner join tableB B on (1=1)
Does anyone has any clue how to do it?
Thanks a lot
Kostas
You will have to go with a custom query using #Query annotation.
#Query("SELECT column1, column2 FROM A tb1, B tb2 WHERE ...")
Like this.
Suppose I have some generic tables apple, orange etc and a table note which contains notes about a row in one of my generic table. The note is stored by saving the entity_type (e.g. the table name) and entity_id (e.g. the id of the row).
I'm trying to make a unidirectional One-to-Many mapping from apple to note. Effectively creating this relationship:
SELECT *
FROM apple f
INNER JOIN note n
ON f.id = n.entity_id
AND n.entity_type = 'apple'
I've been trying something like:
#Entity
public class Apple {
...
#OneToMany
#JoinColumn(name = "entity_id", referencedColumnName = "id")
#WhereJoinTable(clause = "entity_type = 'apple'")
private Set<Note> changeNotes = new HashSet<>();
Which isn't working (error is #WhereJoinTable on an association without join table). Any ideas?
Update:
I think this is the sort of thing I"m trying to do https://docs.oracle.com/html/E13946_02/ref_guide_mapping_notes_nonstdjoins.html
However hibernate is looking for a column instead of just using the string...
I need to make a query inside a DAO using hibernate criteria, but im not sure how.
I have 2 entities, A and B, and an association table, that contains both A and B ID's.
A doesnt know B, and B doesnt know A.
I want to find all A's that are associated with a certain B, using criteria.
I made a diagram, hope it helps to explain.
Example image
As you can see, table A have 3 records, table B have 3 records too and table AssocAB 3 records as well. I want to find all A's that are associated in AssocAB with B1. The query should return A1 and A3.
is it possible?
Here's the classes, and the relationship annotated.
Entity A: No annotation
Entity B: Have a Set of Entity A
#ManyToMany
#JoinTable(name = "Assoc_AB", joinColumns = { #JoinColumn(name = "ID_B")}, inverseJoinColumn = { #JoinColumn(name = "ID_A")})
#ForeignKey(name = "FK_A_B", inverseName = "FK_B_A")
public set<A> getA(){
return this.listOfA;
}
And no class for association class, the mapping on B creates the assoc table.
Thanks in advance.
I tried to write a criteria query with your indications, but it's not easy because you tell that A and B tables have a int ID, but then you put Strings in your rows ("A1", "B1"...). I supposed that your id is a String instead of an int. You should have something like this:
List<A> listOfA = new ArrayList<A>();
Criteria criteria = session.createCriteria(B.class, "b");
criteria.add(Restrictions.eq("b.id", "B1"));
List<B> listOfBs = criteria.list();
for (B b : listOfBs) {
listOfA.addAll(b.getA());
}
If you have a name property in B class, you would have to modify the restriction:
criteria.add(Restrictions.eq("b.name", "B1"));
I hope this code can help you solve your problem.
We have a DB table that is mapped into a hibernate entity. So far everything goes well...
However what we want is to only map enentitys that satisty a specific criteria, like ' distinct(fieldA,fieldB) '...
Is it possible to map with hibernate and hibernate annotations? How can we do it? With #Filter?
I would recommend that you use #Where annotation. This annotation can be used on the element Entity or target entity of a collection. You provide a clause attribute written in sql that will be applied to any select that hibernate performs on that entity. It is very easy to use and very readable.
Here is an example.
#Entity
//I am only interested in Donuts that have NOT been eaten
#Where(clause = "EATEN_YN = 'N'")
public class Donut {
#Column(name = "FILLING")
private String filling;
#Column(name = "GLAZED")
private boolean glazed = true;
#Column(name = "EATEN_YN")
private boolean eaten = false;
...
}
You could create a view and then map that view to entity:
create view my_data as
select ... from ...
#Entity(table="my_data")
public class MyData { ... }
One option is to map the table normally, then you could fetch your always entities through a query or a filter.
You could also make a native SQL query and map the entity on the results:
Query q = sess.createSQLQuery("SELECT DISTINCT fieldA, fieldB FROM some_table")
.addEntity(MyEntity.class);
List<MyEntity> cats = q.list();
It might be also possible to add DISTINCT to this type of HQL query:
select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
Methods 1, 3 and 4 will make a read-only mapping.
Could you be more specific about the criteria you are using? The view approach is more generic since you can't do everything with a hibernate query or filter.
perhaps you could create a new Pojo that encapsulates the fields and the condition that they should statisy . And then then make that class a 'custom user defined type', such that Hibernate will have to use the mapping class that you provide, for mapping that 'type'..
In addition to the options mentioned by Juha, you can also create an object directly out of a SQL query using the NamedNativeQuery and SqlResultSetMapping annotations.
#Entity
#SqlResultSetMapping(name = "compositekey", entities =
#EntityResult(entityClass = MiniBar.class,
fields = { #FieldResult(name = "miniBar", column = "BAR_ID"), })
)
#NamedNativeQuery(name = "compositekey",
query = "select BAR_ID from BAR", resultSetMapping = "compositekey")
#Table(name = "BAR")
public class Bar {
Flavor the SQL query to your taste