Why to use Set in OneToMany Mapping in hibernate - java

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?

Related

Bi-directional one to one mapping only working one way

For some reason with this setup, when saving the transaction with a nested ticket. It will create both and then connect the two. However when I use the transaction repository to find the transaction it will have an attached ticket however when I use the ticket repository and find the ticket, it doesn't have the attached transaction. I generated this relationship with jhipster jdl, not sure what is going wrong here.
Transaction.java
...
#JsonIgnoreProperties(value = { "person", "event", "transaction", "nameTags" }, allowSetters = true)
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private Ticket tickets;
public Ticket getTickets() {
return this.tickets;
}
public Transaction tickets(Ticket ticket) {
this.setTickets(ticket);
return this;
}
public void setTickets(Ticket ticket) {
this.tickets = ticket;
}
...
Ticket.java
...
#JsonIgnoreProperties(value = { "tickets", "membershipLevel", "person", "event" }, allowSetters = true)
#OneToOne(mappedBy = "tickets")
private Transaction transaction;
public Transaction getTransaction() {
return this.transaction;
}
public Ticket transaction(Transaction transaction) {
this.setTransaction(transaction);
return this;
}
public void setTransaction(Transaction transaction) {
if (this.transaction != null) {
this.transaction.setTickets(null);
}
if (transaction != null) {
transaction.setTickets(this);
}
this.transaction = transaction;
}
...
Edit:
Here is the generated SQL output, it is showing here just a normal select wihtout joins from both but transaction has the ticket_id in the transaction table while ticket is doing the same but has no reference and would need to do a join but is not.
Hibernate: insert into ticket (cost_per_ticket, count, event_id, person_id, picked_up, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (cost_sub_items_purchased, date, donation, event_id, event_donation, generic_sub_items_purchased, membership_level_id, notes, number_of_memberships, person_id, tickets_id, total_amount, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select transactio0_.id as id1_23_, transactio0_.cost_sub_items_purchased as cost_sub2_23_, transactio0_.date as date3_23_, transactio0_.donation as donation4_23_, transactio0_.event_id as event_i10_23_, transactio0_.event_donation as event_do5_23_, transactio0_.generic_sub_items_purchased as generic_6_23_, transactio0_.membership_level_id as members11_23_, transactio0_.notes as notes7_23_, transactio0_.number_of_memberships as number_o8_23_, transactio0_.person_id as person_12_23_, transactio0_.tickets_id as tickets13_23_, transactio0_.total_amount as total_am9_23_ from transaction transactio0_
Hibernate: select ticket0_.id as id1_22_, ticket0_.cost_per_ticket as cost_per2_22_, ticket0_.count as count3_22_, ticket0_.event_id as event_id5_22_, ticket0_.person_id as person_i6_22_, ticket0_.picked_up as picked_u4_22_ from ticket ticket0_

Updating ManyToMany relationships in JPA or Hibernate

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

Unnecessary updates in #OneToMany

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 (?, ?, ?)

Foreign key in hibernate

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.

HQL query for retrive rows from ManyToMany Join Table

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

Categories

Resources