I have the following code and the insertion is being done but the query in the query() is not printing the println that its suppose to.
package com;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import roseindia.tutorial.hibernate.Insurance;
import com.Employee;
public class EmployeeEx
{
public static void main(String[] args)
{
Session session = null;
try
{
Transaction transaction = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
File f=new File("c:/Class/Employee1.txt") ;
Scanner scan=new Scanner(f);
transaction = session.beginTransaction();
while(scan.hasNext())
{
Employee em = new Employee();
String line=scan.nextLine();
String empArray[]=line.split(" ");
em.setId(Integer.parseInt(empArray[0]));
em.setName(empArray[1]);
em.setSalary(Double.parseDouble(empArray[2]));
em.setManager(empArray[3]);
session.save(em);
transaction.commit();
}
query();//calling the query method
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.flush();
session.close();
}
}
public static void query()
{
Session session = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.like("manager", "Anurag"));
criteria.add(Restrictions.gt("salary", 1000));
List emp = criteria.list();
for(Iterator it = emp.iterator();it.hasNext();)
{
Employee em = (Employee) it.next();
System.out.println("Id: " +em.getId());;
System.out.println("Name: " +em.getName());
System.out.println("Salary: " +em.getSalary());
System.out.println("Manager: " +em.getManager());
}
session.close();
}
}
This is what is shown on the console:(The insertion is working fine)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEE1 (NAME, SALARY, MANAGER, ID) values (?, ?, ?, ?)
Hibernate: select this_.ID as ID0_, this_.NAME as NAME7_0_, this_.SALARY as SALARY7_0_, this_.MANAGER as MANAGER7_0_ from EMPLOYEE1 this_ where this_.MANAGER like ? and this_.SALARY>? java.lang.Integer
The query() method is not being executed because you are not calling it.
Anyway, you can't call it from main() unless you make it static:
public static void query()
Only the main() method will be executed when you run a class, so after you have added static to the method signature of query(), add this line somewhere to your main() method:
query();
If you are calling the query() method and it still doesn't print anything, then it means that your emp list is empty. Check your database if you have any record matching the restrictions of your query. If you do then check the contents of list emp.
Related
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_
I am trying to insert data of user actions using Spring JPA Single table type inheritance. Below are my classes:
RmlAction.java - The super class
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "entityType")
#Getter
#Setter
#NoArgsConstructor
#Table(name = "rml_actions")
public abstract class RmlAction extends RmlBase {
//attributes
}
RmlProjectAction.java
#Entity
#Getter
#Setter
#DiscriminatorValue(value = "PROJECT")
#NoArgsConstructor
public class RmlProjectAction extends RmlAction {
//constructor
}
RmlEfsAction.java
#Entity
#Getter
#Setter
#DiscriminatorValue(value = "EFS")
#NoArgsConstructor
public class RmlEfsAction extends RmlAction {
//constructor
}
When I try to insert data using ActionRepository, it gives the below error
Hibernate: insert into rml_user (active, creation_date, last_modified_date, object_version, activated, directory_role, efs_id, efs_stack_id, email, login_id, organization, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into rml_efs_action (active, creation_date, last_modified_date, object_version, action_params, action_status, action_type, entity_id, job_id, message, published, user, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2020-02-03 15:53:43,767 WARN [http-nio-5000-exec-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper: SQL Error: 1146, SQLState: 42S02
2020-02-03 15:53:43,768 ERROR [http-nio-5000-exec-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper: Table 'rmldb.rml_efs_action' doesn't exist
Notice here that it is trying to insert into rml_efs_action table and I don't understand the reason. I tried multiple things but nothing works.
I have the following Entity Relations:
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Data
#Entity
public class BatchProcessRecord implements Serializable, Cloneable {
...
#ManyToOne
#JoinColumn(name = "batch_process_id")
private BatchProcess batchProcess;
}
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Data
#Entity
public class BatchProcess implements Serializable, Cloneable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "batchProcess")
private List<BatchProcessRecord> records;
}
And the following code that saves the entities:
// Create batch process
BatchProcess batchProcess = BatchProcess.builder()
....
.records(records)
.build();
// Save entity
batchProcessRepository.save(batchProcess);
In the console, it generates the inserts as expected (with 2 children), but without filling batch_process_id (JoinColumn).
What is happening?
Console:
Hibernate: insert into batch_process (batch_end_date, batch_entries_count, batch_entries_with_issues, batch_name, batch_start_date, report_file_download_date, report_file_name, result_file_name, result_file_upload_date, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into batch_process_record (address_number, batch_process_id, city, first_name, full_street_address, last_name, maternal_name, post_directional, pre_directional, reference_number, ssn, state, street_type, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into batch_process_record (address_number, batch_process_id, city, first_name, full_street_address, last_name, maternal_name, post_directional, pre_directional, reference_number, ssn, state, street_type, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2
Repository:
public interface BatchProcessRepository extends
JpaRepository<BatchProcess, Long> {
}
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.
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