I have two tables employee and bankname. In employee table there is a column bank_name_id which refers the column of bank table.
I have mapped employee bank_name_id with bank bank_name_id with many to one
I'm using spring mvc #RestController while returning it correctly fetch the data from bankname but converting into json its have repeated fetched data
Table 1 Employee Table:
empid empname bank_name_id
1 XXX 1
Table 2 Bankname table
bank_name_id bank_name
1 QQQ
JSON output:
{
empid:1,
empname:"xxx",
bank:{bank_name_id:1,bank_name:QQQ},
bankname:{bank_name_id:1,bank_name:QQQ}
}
this bankname data is repeated
As per you result it show that you have two variables in emp entity one bank and other bankname so please delete bankname variable from emp entity. and then check otherwise share you code here.
Related
I have 2 tables in MySQL database: user and user_additional_details with columns described below.
User
id (auto increment)
userId (unique)
first name
last name
phone
email
User Additional Details
id (auto increment)
userId (matches userId in User)
personalPhone
personalEmail
Table user_additional_details contains 0 or 1 row for each userId in user table.
However, database does not have a foreign key constraint defined. Ideally, columns from user_additional_details should have been added as nullable columns in user table, but that was not done for some unknown reason. Now I need to define the entity for following query.
select user.userId, user.phone, user_a_d.personalPhone
from user
join user_additional_details as user_a_d
on user.userId = user_additional_details.userId
I tried defining JPA entities for the tables, but not able to figure out how to create an entity that uses columns from different tables.
It seems like the SecondaryTable annotation is what you are looking for
Specifies a secondary table for the annotated entity class. Specifying
one or more secondary tables indicates that the data for the entity
class is stored across multiple tables.
Here you find a detailed example of how to use it - http://www.thejavageek.com/2014/09/18/jpa-secondarytable-annotation-example/
Create UserEntity (with all the columns from User table) and UserAdditionalDetailsEntity(with all the columns from user_additional_details table). I assume you are aware how to create JPA entities and map them to database table.
I hope you would have create entity manager factory object in your spring configuration file. With the help of that create entity manager object .
Once EntutyManager Object is created:
Query q= em.createQuery("select user.userId, user.phone, userDetails.personalPhone
from UserEntity user
join UserAdditionalDetailsEntity as userDetails
on user.userId = userDetails.userId");
List<Object[]> resultList= q.getResultList();
Once you get resultList you can iterate over the list of object array and get data.
Each index of the resultList will contain the object array representing one row
Keep in mind that field name mentioned in query should be same as the one mentioned in your JPA Entites.
How do I store integer type list in a comma-separated format in Hibernate?
For example - I have a city table where I have cityId and CityName. In another table I have employee details.An employee can be tagged with multiple city.
I have created another table for employee-city mapping where I want to store the cities in comma separated format.
Table- Employee
----------------------------
Employee_ID Employee_Name
1 Employee 1
2 Employee 2
Table -city
------------------------
City_ID City_Name
1 City_1
2 City_2
Table- Employee-City Mapping
-----------------------
Emp_ID City_id
1 1,2
2 1,2
How to do the this kind actions in Hibernate ? Please help. I am using MySQL as the database backend.
It looks like you are trying to represent a one-to-many relationship.
The conventional SQL way to represent a one-to-many relationship is via multiple rows in a join table. In your case the join table is the employee-city table with a modified design with multiple rows per city rather than multi-valued columns:
Table- Employee-City Mapping
-----------------------
Emp_ID City_id
1 1
1 2
2 1
2 2
JPA (which Hibernate supports) has direct support for mapping these relationships to Collection fields. Your Employee class would have a cities field with type List<City> annotated with #OneToMany.
#Entity
public class Employee {
#Id
#Column(name="Emp_ID")
private long id;
#OneToMany
#JoinColumn(name="Emp_ID", referencedColumnName="City_ID")
private List<City> cities;
// ... rest of the class: constructor, getters, setters
}
The following guide may also help:
https://en.wikibooks.org/wiki/Java_Persistence/OneToMany
I would like to write a JPA entity class that has a one to many relationship. I would like to avoid defining the relationship in the parent class to avoid the data to be loaded every time a reference is made for the object even when there is no need for the associated data. I have read that even with Lazy loading, the data can be loaded so i need to avoid that.
In the following example,
Customer table
------------------------
customerid, customerName
1 John
2 Bob
Order Table - customerId is a foreign key to Customer
orderId, customerId, orderDate
1 1 12MAY2012
1 1 13MAY2012
1 2 16MAY2012
JPA Entities
#Entity
public class Customer {
// all Customer-related fields WITHOUT #OneToMany relationship with Order
}
#Entity
public class Order {
String orderDate;
#ManyToOne
private Customer owner;
}
How would i retrieve data from the customer table based on a condition on the order table? For example, how can i say "Get me all customers who have made an order where the orderDate is between two dates?
using hbm.xml there are query only properties to achieve what you want
http://ayende.com/blog/4054/nhibernate-query-only-properties
I have tables which look like this:
Item table:
ItemName Varchar2(200)
ItemId Number
OwnerId Number
OwnerType number
Person table:
PersonName Varchar2(200)
PersonId Number
Company table:
CompanyName Varchar2(200)
CompanyId Number
When the ownerType for an Item is '1', the ownerId of the item is a foreign key PersonId of the 'person' table. When the OwnerType is '2', the ownerId is a foreign key of the CompanyId of the Company table.
I didn't do the data modelling & I don't have the option of changing the schema.
I'd like to solve two problems:
(1) I'd like a mapping file for the Item table which would give me the items's owner.
(2) I'd like mapping files for the Person & Company tables which would give me the Items owned by the Person or Company, respectively.
Note: a CompanyId and a PersonId can be the same number, so an item is only owned by a Person when person.personid = item.ownerid and item.ownertype = 1.
I can control the mapping files & the object diagram, so I could create an Owner interface or super-class.
Can Hibernate do this sort of thing?
Case 1: you can use the concept of Table per class hierarchy.
Case 2: map items as set for person/company class with where
condition on the set mapping.
Imagine a table emp:
CREATE TABLE emp
( id NUMBER
, name VARCHAR
, dept_code VARCHAR
)
and a table dept:
CREATE TABLE dept
( code VARCHAR
, name VARCHAR
)
emp.dept_code references dept.code as a ForeignKey.
These tables are mapped to JPA Entities, and the ForeignKey is modeled as an association:
#ManyToOne
#JoinColumn(name = "dept_code")
private Department department;
Given following data:
emp dept
---------------- ------------------
1 John SALS SALS Sales
2 Louis SALS SUPT Support
3 Jack SUPT
4 Lucy SUPT
I would like to write a JPA query that returns all Emloyees in the Support Department. Assume I know the PrimaryKey of the Support Department (SUPT)
I guess that would be:
SELECT emp
FROM Employee emp JOIN emp.department dept
WHERE dept.code = 'SUPT'
Question:
As the Department key SUPT code is available in the emp table, is there a way to rewrite the JPA query by avoiding the JOIN to the Department Entity?
Would this result in a performance improvement? Or is a JPA implementation (like Hibernate) smart enough to avoid the database join to the dept table?
You would usually write the query as
select emp
from employee emp
where emp.department.code = 'SUPT'
and let your provider figure out the best way to come up with the result. In the case of hibernate, yes, it is smart enough to realize it can just look at the join column.
edit : It is worth noting, that you haven't set up lazy loading in your annotations, so it's going to join the table in to create the department entity anyway :)