Process finished with exit code 1 after Hibernate query on abstract class - java

I'm trying to implement a Jpa Repository for an Entity that's derived from an abstract class.
The base, abstract class:
#MappedSuperclass
public abstract class BaseProduct {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String brand;
private int price;
private int availability;
private String description;
//constructors getters and setters omitted
}
The derived class:
#Entity
public class Product extends BaseProduct {
//constructors omitted
}
The JpaRepository extension:
#Repository
public interface ProductRepository extends JpaRepository<Product, Long > {
}
Where it breaks:
#Bean
public CommandLineRunner commandLineRunner(ProductRepository productRepository) {
Log log = LogFactory.getLog(this.getClass());
return (args) -> {
ProductInfo p1 = new ProductInfo("Hook1", "lorem", 2, 50, "desc");
ProductInfo p2 = new ProductInfo("Hook2", "lorem", 2, 50, "desc");
Product b1 = new Product(p1);
productRepository.save(b1);
productRepository.save(new Product(p2));
productRepository.findAll().forEach(product -> log.info(product.getName()));
};
This is the outcome:
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into product (availability, brand, description, name, price, id) values (?, ?, ?, ?, ?, ?)
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into product (availability, brand, description, name, price, id) values (?, ?, ?, ?, ?, ?)
Hibernate: select product0_.id as id1_0_, product0_.availability as availabi2_0_, product0_.brand as brand3_0_, product0_.description as descript4_0_, product0_.name as name5_0_, product0_.price as price6_0_ from product product0_
Process finished with exit code 1
Saving works fine.Objects are properly persisted into the mysql database
Here are the final lines of the mariadb general logs:
86 Query insert into product (availability, brand, description, name, price, id) values (50, 'lorem', 'desc', 'Hook2', 2, 2)
86 Query commit
86 Query SET autocommit=1
86 Query SET autocommit=0
86 Query select product0_.id as id1_0_, product0_.availability as availabi2_0_, product0_.brand as brand3_0_, product0_.description as descript4_0_, product0_.name as name5_0_, product0_.price as price6_0_ from product product0_
86 Query rollback
86 Query SET autocommit=1
86 Quit
87 Quit
88 Quit
89 Quit
90 Quit
91 Quit
92 Quit
93 Quit
94 Quit
95 Quit
.count works fine, however, I can't read any data back from the database. I tried doing it without the Entity abstraction and it worked just fine.

Related

Why to use Set in OneToMany Mapping in hibernate

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?

JPA change are not persisted in database

I'm quite new to spring and I'm trying to build a rest api.
My aim is to create a small quiz game.
A Game is composed by Rounds (1:n).
In Round, I have fields where I set the user response.
This is my RoundRepository class :
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.utouch.nymeria.quizzServer.models.Round;
public interface RoundRepository extends JpaRepository<Round, Long> {
#Modifying
#Query("update Round r set r.reply_player = ?1 where r.id = ?2")
#Transactional
void addPlayerReply(int reply_number, Long roundID);
#Modifying
#Query("update Round r set r.reply_opponent = ?1 where r.id = ?2")
#Transactional
void addOpponentReply(int reply_number, Long roundID);
}
GameRepository.java :
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.utouch.nymeria.quizzServer.models.Game;
import org.utouch.nymeria.quizzServer.models.User;
public interface GameRepository extends JpaRepository<Game, Long> {
List<Game> findByPlayer(User player);
}
Game.java :
#Entity
public class Game implements Serializable {
private static final long serialVersionUID = 2L;
#Id
#GeneratedValue
private Long id;
#ManyToOne
private User player;
#ManyToOne
private User opponent;
private int player_score=0;
private int opponent_score=0;
private Boolean ended;
#Temporal(TemporalType.TIMESTAMP)
private Date startDate = new Date();
#OneToMany(targetEntity=Round.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private List<Round> rounds = new ArrayList<Round>();
public Game(User player, User opponent) {
super();
this.player = player;
this.opponent = opponent;
this.ended = false;
}
public Game() {
super();
this.ended = false;
}
// ... getter / setter
}
And here, my logic :
// create user
User jesaispas = userRepo.save(new User("jesaispas","pass"));
User morgan = userRepo.findByLogin("morgan");
// create first game
Game game1 = new Game(morgan,jesaispas);
gameRepo.save(game1);
// add first round
Round r1 = new Round(q1.getIdQuestion());
//roundRepo.save(r1);
game1.getRounds().add(r1);
gameRepo.save(game1);
roundRepo.addPlayerReply(3, r1.getId());
roundRepo.addOpponentReply(1, r1.getId());
Round r2 = new Round(q2.getIdQuestion());
//roundRepo.save(r2);
game1.getRounds().add(r2);
gameRepo.save(game1);
roundRepo.addPlayerReply(4, r2.getId());
And there are hibernate log :
Hibernate: insert into round (round_id, questionid, reply_opponent, reply_player, start_date) values (null, ?, ?, ?, ?)
Hibernate: insert into game_rounds (game, rounds) values (?, ?)
Hibernate: update round set reply_player=? where round_id=?
Hibernate: update round set reply_opponent=? where round_id=?
Hibernate: select game0_.game_id as game_id1_0_1_, game0_.ended as ended2_0_1_, game0_.opponent as opponent6_0_1_, game0_.opponent_score as opponent3_0_1_, game0_.player as player7_0_1_, game0_.player_score as player_s4_0_1_, game0_.start_date as start_da5_0_1_, rounds1_.game as game1_0_3_, round2_.round_id as rounds2_1_3_, round2_.round_id as round_id1_3_0_, round2_.questionid as question2_3_0_, round2_.reply_opponent as reply_op3_3_0_, round2_.reply_player as reply_pl4_3_0_, round2_.start_date as start_da5_3_0_ from game game0_ left outer join game_rounds rounds1_ on game0_.game_id=rounds1_.game left outer join round round2_ on rounds1_.rounds=round2_.round_id where game0_.game_id=?
Hibernate: select user0_.id as id1_4_0_, user0_.auth_token as auth_tok2_4_0_, user0_.email as email3_4_0_, user0_.last_activity as last_act4_4_0_, user0_.login as login5_4_0_, user0_.password as password6_4_0_, user0_.registration_date as registra7_4_0_, user0_.salt as salt8_4_0_ from user user0_ where user0_.id=?
Hibernate: select user0_.id as id1_4_0_, user0_.auth_token as auth_tok2_4_0_, user0_.email as email3_4_0_, user0_.last_activity as last_act4_4_0_, user0_.login as login5_4_0_, user0_.password as password6_4_0_, user0_.registration_date as registra7_4_0_, user0_.salt as salt8_4_0_ from user user0_ where user0_.id=?
Hibernate: insert into round (round_id, questionid, reply_opponent, reply_player, start_date) values (null, ?, ?, ?, ?)
Hibernate: insert into round (round_id, questionid, reply_opponent, reply_player, start_date) values (null, ?, ?, ?, ?)
Hibernate: insert into game_rounds (game, rounds) values (?, ?)
Hibernate: insert into game_rounds (game, rounds) values (?, ?)
Hibernate: update round set reply_player=? where round_id=?
The problem is: the modification is not persisted, but as week can see, there is update request done by hibernate. So, Why get I do a ```findAll()``` the value is not updated ?
Do you know where is located the problem?
put #Transactional on top of the implemented class of JpaRepository ( the class that implements RoundRepository). Then you should be able to see your data is persisted permanently.

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