I have model object as follows
Employee.java
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
#SequenceGenerator(name = "emp_seq", sequenceName = "seq_employee")
#GeneratedValue(generator = "emp_seq")
#Column(name = "EMPLOYEE_ID")
private Integer employeeId;
#Column(name = "EMPLOYEE_NAME")
private String employeeName;
}
Department.java
#Entity
#Table(name = "DEPARTMENT")
public class Department {
#Id
#Column(name = "DEPARTMENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer departmentId;
#Column(name = "DEPARTMENT_NAME")
private String departmentName;
#Column(name = "LOCATION")
private String location;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "DEPARTMENT_ID")
private List<Employee> employees = new ArrayList<>();
}
while saving this it is generating two extra update statements.
Test class
Employee e1 = new Employee();
e1.setEmployeeName("Employee-1");
Employee e2 = new Employee();
e2.setEmployeeName("Employee-2");
Department d = new Department();
d.setDepartmentName("Test");
d.setLocation("Test");
d.getEmployees().add(e1);
d.getEmployees().add(e2);
em.getTransaction().begin();
em.persist(d);
em.getTransaction().commit();
on committing the following statements are generated...
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
my question here is why 2 extra update(marked by *) statements are needed?
That's the order on which Hibernate does the operations normally. Take a look at this
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29
According to this documentation:
Execute all SQL (and second-level cache updates) in a special order so
that foreign-key constraints cannot be violated:
When you add Employees to a Department, employees must have a Department ID so that's the reason why Hibernate do an extra update.
If you want to avoid it you can create first the department, and then the employees adding manually Department id
Due to the #OneToMany #JoinColumn(name = "DEPARTMENT_ID") that annotates the attribute Department.employees the table
EMPLOYEE has a foreign key to the table DEPARTMENT. When you persiste the new department with the two employees a new row is inserted into the table DEPARTMENT and two rows are inserted into the table EMPLOYEE but the column DEPARTMENT_ID is null. Then two updates are executed to set this column and relate the EMPLOYEE rows with the DEPARTMENT row.
The question is why this is not done in one step, i.e. instead of executing the following:
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
the following should be executed:
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID, DEPARTMENT_ID) values (?, ?, ?)
Related
I have two Entity like below...
#Entity
#Table(name = "USER")
public class User {
#Id
private Long id;
private String name;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "groupMemberList")
#Fetch(FetchMode.SELECT)
private List<Group> groupList = new ArrayList<>();
// Getters - Setters
}
#Entity
#Table(name = "GROUP")
public class Group {
#Id
private Long id;
private String name;
#ManyToMany(fetch = FetchType.LAZY/*, mappedBy = "groupList"*/)
#Fetch(FetchMode.SELECT)
#JoinTable(name = "SEC_GROUP_VS_MEMBER", joinColumns = #JoinColumn(name = "GROUP_ID"),
inverseJoinColumns = #JoinColumn(name = "MEMBER_ID"))
private List<User> groupMemberList;
// Getters - Setters
}
I want to update the User sometimes and also Group sometimes with the methods below...
Method#1
public boolean updateGroup(Long groupId, List<Staff> groupMemberList) {
Group group = hibernateTemplate.get(Group.class, groupId);
group.setGroupMemberList(groupMemberList);
hibernateTemplate.merge(group); // Group updated with the users
return true;
}
Method#2
public boolean updateUser(Long userId, List<Group> groupList) {
User user = hibernateTemplate.get(User.class, userId);
user.setGroupList(groupList);
hibernateTemplate.merge(user); // User not updated with the groups
return true;
}
The first method works fine but not the second one. BUT when I move the join table from Group.class to User.class then second method works fine and not the first one.
The issue is an Owning Entity issue.
Assuming that Staff is a subclass of User, your issue is that only one side of the relationship is the owning entity. The mappedBy = "groupMemberList" makes the Group entity the owning entity and so only changes to that entity are persisted. This means that you have to update the groupMemberList in the Group entity in both cases. If you have a list of groups for a User then you have to iterate over the list of groups and add the User to it. The groupList in User is only for retrieval.
Given User and GroupMember entities:
#Entity
public class User {
#Id #GeneratedValue
private Long id;
#ManyToMany(mappedBy = "groupMemberList")
private List<GroupMember> groupList;
#Entity
public class GroupMember {
#Id #GeneratedValue
private Long id;
#ManyToMany
private List<User> groupMemberList;
Then:
// create starting user and membergroup
tx.begin();
User user = new User();
em.persist(user);
GroupMember group = new GroupMember();
em.persist(group);
tx.commit();
em.clear();
// update users for groupId 2
System.out.println("update users for groupId 2");
tx.begin();
List<User> users = new ArrayList<>();
users.add(user);
group.setGroupMemberList(users);
em.merge(group);
tx.commit();
em.clear();
// update groups for userId 1 -- doesn't work, not owner of relationship
System.out.println("update groups for userId 1 -- doesn't work, not owner of relationship");
tx.begin();
List<GroupMember> groups = new ArrayList<>();
groups.add(group);
user.setGroupList(groups);
em.merge(user);
tx.commit();
em.clear();
// update groups for userId 1 -- works
System.out.println("update groups for userId 1 -- works");
tx.begin();
for ( GroupMember groupMember: groups) {
groupMember.getGroupMemberList().add(user);
em.merge(groupMember);
}
tx.commit();
em.clear();
Gives the following SQL output:
Hibernate: insert into User (id) values (?)
Hibernate: insert into GroupMember (id) values (?)
update users for groupId 2
Hibernate: select groupmembe0_.id as id1_0_0_ from GroupMember groupmembe0_ where groupmembe0_.id=?
Hibernate: select groupmembe0_.groupList_id as groupLis1_1_0_, groupmembe0_.groupMemberList_id as groupMem2_1_0_, user1_.id as id1_4_1_ from GroupMember_User groupmembe0_ inner join User user1_ on groupmembe0_.groupMemberList_id=user1_.id where groupmembe0_.groupList_id=?
Hibernate: select user0_.id as id1_4_0_ from User user0_ where user0_.id=?
Hibernate: insert into GroupMember_User (groupList_id, groupMemberList_id) values (?, ?)
update groups for userId 1 -- doesn't work, not owner of relationship
Hibernate: select user0_.id as id1_4_0_ from User user0_ where user0_.id=?
Hibernate: select groupmembe0_.id as id1_0_0_ from GroupMember groupmembe0_ where groupmembe0_.id=?
update groups for userId 1 -- works
Hibernate: select groupmembe0_.id as id1_0_0_ from GroupMember groupmembe0_ where groupmembe0_.id=?
Hibernate: select groupmembe0_.groupList_id as groupLis1_1_0_, groupmembe0_.groupMemberList_id as groupMem2_1_0_, user1_.id as id1_4_1_ from GroupMember_User groupmembe0_ inner join User user1_ on groupmembe0_.groupMemberList_id=user1_.id where groupmembe0_.groupList_id=?
Hibernate: delete from GroupMember_User where groupList_id=?
Hibernate: insert into GroupMember_User (groupList_id, groupMemberList_id) values (?, ?)
Hibernate: insert into GroupMember_User (groupList_id, groupMemberList_id) values (?, ?)
Reference: MappedBy in bi-directional #ManyToMany : what is the reason
JPA - difference in the use of the mappedBy property to define the owning entity
I have two tables with a one-to-many relationship. I want to fetch those records and insert into another database which having same table by changing the primary key.
My application entity class
#Entity
#Table(name = "EM_APPLICATION")
public class ApplicationTable {
#Id
private int APPLICATION_ID;
#Id
private String CUSTOMER_ID;
private String LAST_NAME;
private String FIRST_NAME;
#OneToMany( fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumns({ #JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID"),
#JoinColumn(name = "APPLICATION_ID", referencedColumnName = "APPLICATION_ID") })
private Set<AddressTable> address;
//Getters and setters
}
Address entity class..
#Entity
#Table(name="EM_APPL_ADDRESS")
public class AddressTable{
#Id
private int APPLICATION_ID;
#Id
private String CUSTOMER_ID;
#Id
private String ADDRESS_TYPE;
//Getters and setters
}
I have to execute a method for fetching records from DB using hibernate:
public void execute(String applId, String customerId) {
Session session = HibernateQAUtil.openSession();
Transaction tx = session.beginTransaction();
String hql = "FROM ApplicationTable WHERE CUSTOMER_ID =:CUSTOMER_ID AND APPLICATION_ID =:APPLICATION_ID";
Query query = session.createQuery(hql);
query.setParameter("CUSTOMER_ID", customerId);
query.setParameter("APPLICATION_ID", Integer.parseInt(applId));
List<ApplicationTable> list = query.list();
tx.commit();
session.close();
ApplicationTable applVO = list.get(0);
insertApplication(applVO );
}
After fetching the records, I am changing APPLICATION_ID, CUSTOMER_ID and some other columns in address table and after inserting in another database.
private void insertApplication(ApplicationTable emApplVO) {
applVO.setAPPLICATION_ID(123456);
applVO.setCUSTOMER_ID("88888888");
Set<AddressTable> addressSet = emApplVO.getAddress();
for (AddressTable address : addressSet) {
address.setAPPLICATION_ID(123456);
address.setCUSTOMER_ID("88888888");
address.setZIP(500032);
}
Session session1 = HibernateUtil.openSession();
Transaction beginTransaction = session1.beginTransaction();
session1.save(emApplVO);
beginTransaction.commit();
session1.close();
}
Hibernate queries in console log are... (below mentioned queries are too large so copied to some extent only..)
Hibernate: select em_applica0_.CUSTOMER_ID as CUSTOMER1_0_,em_applica0_.APPLICATION_ID as APPLICAT2_0_,em_applica0_.ARCHIVE_IND as ARCHIVE8_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: select address0_.CUSTOMER_ID as CUSTOMER1_0_1_, address0_.APPLICATION_ID as APPLICAT2_0_1_, address0_.ADDRESS_TYPE as ADDRESS3_1_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: insert into EM_APPLICATION (CUSTOMER_ID, APPLICATION_ID, APPLICATION_NBR, APPLICATION_STATUS, APPLICATION_TYPE) values (?, ?, ?, ?)
Hibernate: insert into EM_APPL_ADDRESS (CUSTOMER_ID, APPLICATION_ID, ADDRESS_TYPE) values (?, ?, ?)
Question 1: in the insert method, I have assigned address to addresSet and made some changes in addresSet, after making those changes, I am not assigned the addressSet to applVO (i.e. not written applVO.setAddress(addresSet )) but it inserted a record with updated values into the Address table. What is happening here?
When I am changing code inside insertApplication(ApplicationTable emApplVO) method to
private void insertApplication(ApplicationTable emApplVO) {
applVO.setAPPLICATION_ID(123456);
applVO.setCUSTOMER_ID("88888888");
Set<AddressTable> addressSet = emApplVO.getAddress();
Set<AddressTable> newAddressSet = new HashSet<AddressTable>();
for (AddressTable address : newAddressSet) {
address.setAPPLICATION_ID(emApplVO.getAPPLICATION_ID());
address.setCUSTOMER_ID(emApplVO.getCUSTOMER_ID());
address.setZIP(500032);
newAddressSet.add(address);
}
emApplVO.setAddress(null);
emApplVO.setAddress(newAddressSet);
Session session1 = HibernateUtil.openSession();
Transaction beginTransaction = session1.beginTransaction();
session1.save(emApplVO);
beginTransaction.commit();
session1.close();
}
Hibernate queries in console log are... It also executing update ...
Hibernate: select em_applica0_.CUSTOMER_ID as CUSTOMER1_0_,em_applica0_.APPLICATION_ID as APPLICAT2_0_,em_applica0_.ARCHIVE_IND as ARCHIVE8_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: select address0_.CUSTOMER_ID as CUSTOMER1_0_1_, address0_.APPLICATION_ID as APPLICAT2_0_1_, address0_.ADDRESS_TYPE as ADDRESS3_1_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: insert into EM_APPLICATION (CUSTOMER_ID, APPLICATION_ID, APPLICATION_NBR, APPLICATION_STATUS, APPLICATION_TYPE) values (?, ?, ?, ?)
Hibernate: insert into EM_APPL_ADDRESS (CUSTOMER_ID, APPLICATION_ID, ADDRESS_TYPE) values (?, ?, ?)
update EM_APPL_ADDRESS set CUSTOMER_ID=?, APPLICATION_ID=? where CUSTOMER_ID=? and APPLICATION_ID=? and ADDRESS_TYPE=?
Question 2: why is the update query executed?
Question 3: while using List<AddressTable> instead of Set<AddressTable>, I got some errors. What is the difference?
I want to persist an entity which both doesn't have a generated value for the identifier and also cascade persists another entity. However this combination doesn't seem to be possible. I'm using Spring Data JPA for saving the entities.
Let's say you have two entities, for e.g. Student and Address. For students you want to keep their registration date (let's assume it's always unique), name and address. From the address you want to only save the street for simplicity sake. When saving the Student entity you want to cascade persist the Address entity. So you create the following entities.
#Entity
public class Student {
#Id
private LocalDateTime registrationDateTime;
#Column(nullable = false)
private String name;
#ManyToOne(targetEntity = Address.class, cascade=CascadeType.PERSIST)
private Address address;
public Student(LocalDateTime registrationDateTime, String name, Address address) {
setRegistrationDateTime(registrationDateTime);
setName(name);
setAddress(address);
}
public Student() {
}
// ...getters and setters omitted...
}
and:
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String street;
public Address(String street) {
setStreet(street);
}
public Address() {
}
// ...getters and setters omitted...
}
When you execute the following code both entity are persisted but street is NULL.
Student student = new Student(LocalDateTime.now(), "John Doe");
student.setAddress(new Address("Mainstreet"));
studentRepository.save(student);
When I remove the #Id annotation from the LocalDateTime property and add the following code then the address is saved correctly.
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
These are the queries which Hibernate executes (it seems odd by the way that it's inserting the student first since that entity needs the id of the address).
Hibernate:
alter table Student
drop constraint FKf12myy73nsf6soln9xli8th80
Hibernate:
drop table Address
Hibernate:
drop table Student
Hibernate:
drop sequence hibernate_sequence restrict
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:
create table Address (
id integer not null,
street varchar(255),
primary key (id)
)
Hibernate:
create table Student (
dateTime timestamp not null,
name varchar(255) not null,
address_id integer,
primary key (dateTime)
)
Hibernate:
alter table Student
add constraint FKf12myy73nsf6soln9xli8th80
foreign key (address_id)
references Address
Hibernate:
select
student0_.dateTime as dateTime1_3_0_,
student0_.address_id as address_3_3_0_,
student0_.name as name2_3_0_
from
Student student0_
where
student0_.dateTime=?
Hibernate:
values
next value for hibernate_sequence
Hibernate:
insert
into
Student
(address_id, name, dateTime)
values
(?, ?, ?)
Hibernate:
insert
into
Address
(street, id)
values
(?, ?)
Hibernate:
update
Student
set
address_id=?,
name=?
where
dateTime=?
I have two simple tables Customers and Orders with relation oneToMany from customer to Orders table.
This is my Customers.java
#Entity
public class Customers implements Serializable {
#Id
#GeneratedValue
private int cID;
private String name;
private String email;
// getter and setters
}
And this is Orders.java:
#Entity
public class Orders implements Serializable {
#Id
#GeneratedValue
private int orderID;
private int cId;
#Column(nullable = false)
#Temporal(TemporalType.DATE)
private Date date;
#ManyToOne(cascade = CascadeType.ALL)
private Customers customers;
// getter and setters
}
Now, i am going to insert two record in Orders table:
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Orders orders1 = new Orders();
Orders orders2 = new Orders();
Customers customer = new Customers();
customer.setName("c1");
customer.setEmail("abc#gmail.com");
orders1.setDate(new Date());
orders2.setDate(new Date());
orders1.setCustomers(customer);
orders2.setCustomers(customer);
session.save(orders1);
session.save(orders2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
This is the result in console:
Hibernate: alter table Orders drop foreign key FK_hmbx2rg9tsgqikb3kodqp90c4
Hibernate: drop table if exists Customers
Hibernate: drop table if exists Orders
Hibernate: create table Customers (cID integer not null auto_increment, email varchar(255), name varchar(255), primary key (cID))
Hibernate: create table Orders (orderID integer not null auto_increment, cId integer not null, date date not null, customers_cID integer, primary key (orderID))
Hibernate: alter table Orders add constraint FK_hmbx2rg9tsgqikb3kodqp90c4 foreign key (customers_cID) references Customers (cID)
Feb 24, 2015 1:58:52 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Customers (email, name) values (?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
And this is the result tables:
Why the cID in Orders table (which is a foreign key references to customers) is 0?
It should be 1.
It think in your orders table customers_cId is the actual foreign key reference column to the customers table. As you haven't gave any column name explicitly, it internally took column name as customers_cId by joining the variables from both the entities. customers from the orders and cId from the customers entity.
Just to verify you can try giving some other name using #JoinColumn annotation.
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="order_cId")
private Customers customers;
And cId in orders table is just one more independent column, as you have not set any value to it, its taking the default value as 0. Try setting some random value to it.
I'm working on website where user can subscribe to Organisation.
when I'm going to implement Subscribe function and I face the following problem.
In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user.
And In Hibernate I can't create Table without primary key.but in join table one user can subscribe to many organisation and one organisation has many subscriber so primary key are repeat and I got exception ERROR: Duplicate entry '1' for key 'PRIMARY'.
hibernate.cfg.xml contain
<mapping class="model.User"/>
<mapping class="model.Post"/>
<mapping class="model.UserSubscribes"/>
User.java
package model;
#Entity
#Table(name="user",
uniqueConstraints = {#UniqueConstraint(columnNames={"email"})}
)
#org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)
public class User implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long userId;//1
private String email;//1
private String password;//
public User(long userId, String email, String password){
this.userId = userId;
this.email = email;
this.password = password;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name="UserSubscribes",
joinColumns={ #JoinColumn(name="userId",referencedColumnName="userId") },
inverseJoinColumns={ #JoinColumn(name="orgId", referencedColumnName="orgId") }
)
private Collection<Organisation> orgSubscribes = new ArrayList<Organisation>();
//Getter & Setter
}
Organisation.java
package model;
#Entity
#Table(name="org",
uniqueConstraints = {#UniqueConstraint(columnNames={"email"})}
)
#org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)
public class Organisation implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long orgId;
private String email;
private String password;
public Organisation(long orgId, String email, String password){
this.orgId = orgId;
this.email = email;
this.password = password;
}
//Getter & Setter
}
UserSubscribes.java
package model;
#Entity
#Table(name="UserSubscribes")
public class UserSubscribes implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long userId;
private long orgId;
//Getter & Setter
}
Subscribe.java
package view.action;
public class Subscribe extends ActionSupport {
public String execute(){
Session session = HibernateUtill.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
User u1 = new User(1, "ppp", "ppp");
User u2 = new User(2, "qqq", "qqq");
Organisation o1 = new Organisation(1, "ppp", "ppp");
Organisation o2 = new Organisation(2, "qqq", "qqq");
Organisation o3 = new Organisation(3, "www", "www");
Organisation o4 = new Organisation(4, "eee", "eee");
session.save(o1);
session.save(o2);
session.save(o3);
session.save(o4);
session.save(u1);
session.save(u2);
u1.getOrgSubscribes().add(o1);
u1.getOrgSubscribes().add(o2);
u1.getOrgSubscribes().add(o3);
session.saveOrUpdate(u1);
session.getTransaction().commit();
return SUCCESS;
}
}
and I got this output and error
Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'PRIMARY'
If I remove <mapping class="model.UserSubscribes"/> from hibernate.cfg.xml mapping then it works perfect as following output.
Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
and output is
but I can't retrieve rows(using HQL) from it without map this table in hibernate.cfg.xml file.
If any possible solution for this problem I'm really thankful to you.
Thank you in advance.
The join table should not be mapped as an entity. You simply need User, Organization, and a ManyToMany association between those 2 entities.
In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user
That can be done with the association:
User user = em.find(User.class, userId);
Set<Organization> organizations = user.getOrganizations();
or with a simple JPQL query:
select o from User u inner join u.organizations o where u.id = :userId
Thanks JB Nizet
I implement code as you suggest and it works perfect.
Here is Solved Code.
GetSubscriber.java
package view.action;
public class GetSubscriber extends ActionSupport {
public String execute(){
Session session = HibernateUtill.getSessionFactory().getCurrentSession();
session.beginTransaction();
User u = (User) session.get(User.class, (long)1);
List<Organisation> s = (List<Organisation>) u.getOrgSubscribes();
for(int i=0;i<s.size();i++){
System.out.println(s.get(i).getOrgId() + " " + s.get(i).getEmail());
}
return SUCCESS;
}
}
Output:
1 ppp
2 qqq
3 www