Data doesn't retrieving with Hibernate max query - java

I'm using Hibernate 4.2.6 with Java DB
Here's my
RegisterationHelper.java
org.hibernate.Transaction tx = session.beginTransaction();
String uid = std.getUserid();
System.out.println(uid);
Query query = session.createQuery("FROM university.Student");
List<Student> student = query.list();
for(Iterator it= student.iterator(); it.hasNext();)
{
//some code....
{
try
{
tx = session.beginTransaction();
int rgstnum=0;
Query q = session.createQuery("Select max(registrationnumber)from Student");
List currentRegNo = q.list();
rgstnum=(Integer)currentRegNo.get(0)+1;
std.setRegistrationnumber(rgstnum);
sc.setRegistrationnumber(rgstnum);
Serializable objID=session.save(std);
session.saveOrUpdate(sc);
tx.commit();
}
catch(Exception e)
{
}
//priniting sc.getRegistrationnumber() showing null
//priniting sc.getCurseid() has data
and RegistrationForm.java
#ManagedBean
#RequestScoped
public class RegistrationForm {
public String submitAction() {
RegistrationHelper rghp = new RegistrationHelper();
Student std = new Student();
std.setFirstname(getFirstName().toString());
std.setLastname(getLastName().toString());
std.setGender(getGender().toString());
std.setDob(getDateofBirth());
std.setAddress(getAddress().toString());
std.setPhone(getContactNumber().toString());
std.setEmail(getEmailID().toString());
std.setUserid(getUserID().toString());
std.setPassword(getPassword().toString());
Studentcourse sc = new Studentcourse();
sc.setCourseid(getCourse().toString());
String msg = rghp.insertStudent(std, sc);
if(msg.equals("error"))
{
setUserIdError("User Id already exist");
setUserID("");
return "Registration";
}
else
{
return "Success";
}
}`
So I think there is problem only with query Query q = session.createQuery("Select max(registrationnumber)from Student"); that doesn't retrieving registrationumber cause I'm able to store data in Student table if removing code regarding StudentCourse and other thing is getting Info: nested transactions not supported in sever log.
So please if my query is wrong or something else.

I do not think there are problems in the query: the message nested transactions not supported refers to the fact that you open the transaction (session.beginTransaction()) twice, one at the beginning and then again within the cycle. Try to remove the second.

Related

create custom query for liferay default table

I want to know if it's possible to create custom query for liferay default table like user, userGroup...
I looked at the example but they give examples that on the custom tables (guestbook table)
try this code
public List<User> getUserByRecentChat(long userId){
Session session=null;
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
try {
session = sessionFactory.openSession();
String sql = CustomSQLUtil.get(getClass(), "getUserByRecentChat");
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setCacheable(false);
sqlQuery.addEntity("users_", UserImpl.class); // for user table
QueryPos pos = QueryPos.getInstance(sqlQuery);
pos.add(userId);
pos.add(userId);
return (List<User>) sqlQuery.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
sessionFactory.closeSession(session);
}
return null;
}
Yes you can use Custom Query for Liferay Default Tables
Thanks

Hibernate adding new element #oneToMany

what's wrong guys I have that relations in hibernate #oneToMany:
This is in loan class:
#ManyToOne(cascade=CascadeType.ALL)
private users user;
This is in user class:
#OneToMany(mappedBy="user",fetch=FetchType.LAZY)
private Set<loans> loans=new HashSet<loans>(0);
here I have method to insert new loan:
public static void addLoanToUser(Integer userID,String brand,String model,String registration,String loanStart , String loanEnd){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
users user = (users) session.load(users.class, userID);
Set<loans> loanSet = new HashSet();
loans loan = new loans();
loan.setBrand(brand);
loan.setModel(model);
loan.setRegistration(registration);
loan.setLoanStart(loanStart);
loan.setLoanEnd(loanEnd);
loan.setPaydone("no");
loanSet.add(loan);
user.setLoans(loanSet);
session.saveOrUpdate(user);
session.save(loan);
session.getTransaction().commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
When I insert data to the database there is always NULL on Foreign Key.
I tried to find sth on the stack but nothing helped.
Its because you have to set relation on "key holder" in your case that is loan entity. So
users user = (users) session.load(users.class, userID);
loans loan = new loans();
..... setup
loan.setUser(user)
session.saveOrUpdate(user);
And you do realize, that if user will take new loan, you effectively removes other loans of that user (in current session) by setting brand new user.loans set ? :) I wish banking systems work like that :)

Error: Hibernate could not initialize proxy - no Session

ReportService Code
private void generatePaySummary() {
try {
Map params = new HashMap();
params = getOrganizationInfo(params);
params.put("rptsubtitle", "Payroll Date: "+date_formatter.format(tbpaydate.getDate()));
int i = cboDept.getSelectedIndex();
int deptno = 0;
if (i != -1) deptno = (Integer)deptnos.get(i);
ReportService srv = new ReportService();
List empids = srv.getEmployeesInPayroll(deptno, tbpaydate.getDate());
if (!empids.isEmpty()) {
PayslipService.setEmployees(empids);
PayslipService.setPayDate(tbpaydate.getDate());
RepGenService repsrv = new RepGenService();
JRBeanCollectionDataSource jbsrc = new JRBeanCollectionDataSource(PaySummaryFactory.getPaySummary());
repsrv.generateReport(false, "/orgpayroll/reports/jasper/payrollsummary.jasper", true, params, jbsrc);
}
else
SysUtils.messageBox("No employees in payroll on "+date_formatter.format(tbpaydate.getDate())+"!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error" + e.getMessage());
}
}
I am trying to execute a function which will open a jasper report template.
The function works if it will only process 1 employee from the database, but if I process more with the same date, it says Hibernate could not initialize proxy - no Session.
This means that you have one collection with lazy fetchType.
you can solve it by changing it to EAGER mode
So go to ReportService class and turn your employee collection's fetchType to EAGER. Or add (fetch=fetch = FetchType.EAGER)

Hibernate output name of columns

i am want output name of columns from table of my database on MySql. I am use Rest on Java, maven, tomcat, hibernate.
this code not work:
personDao.java:
public List<Person> getHeaders() {
List<Person> persons = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
persons = session.createQuery("SHOW FIELDS FROM person").list();
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
} finally {
if (session != null) {
session.close();
}
}
return persons;
}
service.java:
#GET
#Path("/getHeaders")
#Produces(MediaType.APPLICATION_JSON)
public List<Person> getHeaders() {
return personDao.getHeaders();
}
Please help me, how output name of columns ?
You can use the information_schema database and then use a standard hibernate query definition. In the information schema you can use a query as:
select * from COLUMNS WHERE table_name='person';
You can see this post: Get column name of property mapped with Hibernate
((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
.getProperty("myProperty").getColumnIterator().next()).getName();
and Get table column names in Hibernate

Projection Queries: How to load raw String using JPA for new Entity in AppEngine?

How do I load a list of Strings for a brand new, empty, non-existent table in AppEngine? I tried to follow this example:
http://www.objectdb.com/java/jpa/query/jpql/select#Projection_of_Path_Expressions_
but it gives me an error:
Caused by: javax.persistence.PersistenceException: Class AdminUser for query has not been resolved. Check the query and any imports/aliases specification
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class AdminUser for query has not been resolved. Check the query and any imports/aliases specification
Here is the code:
public java.util.List<String> getAdmin() {
EntityManager em = EMF.get().createEntityManager();
try {
TypedQuery<String> tq = em.createQuery("select au.email from AdminUser as au", String.class);
return tq.getResultList(); ///// <=== EXCEPTION
I don't actually want to use an AdminUser class. I only want the single column of Strings. It is not obvious how to create a new empty table on AppEngine.
GAE Datastore is a schemaless NoSQL database. There are no tables. Only entities that must have a kind, an id and can have an arbitrary set of properties.
You can use Datastore via JPA API, to give you nice typed Java classes instead of low-level untyped entities.
AppEngine does not support JPA raw primitive queries as in the example link. I had to use the DatastoreService API directly. Here is what I tried. Needs some cleaning as many of the things did not work, but this did.
public java.util.List<String> getAdmin() {
log.info("getAdmin()");
// AppEngine does not support strong consistency... will frequently return stale results. Setting read policy won't work.
// Construct a read policy for strong consistency
ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG);
// Set the read policy
DatastoreServiceConfig consistentConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy);
// Get Datastore service with the given configuration
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService(consistentConfig);
com.google.appengine.api.datastore.Query query = new com.google.appengine.api.datastore.Query("AdminUser");
// DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
java.util.List<Entity> events = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
ArrayList<String> al = new ArrayList<String>();
for(Entity entity: events) {
String s = entity.getProperty("email").toString();
al.add(s);
}
if(true) return al;
#SuppressWarnings("unused")
EntityManager em = EMF.get().createEntityManager();
try {
TypedQuery<String> tq = em.createQuery("select au.email from AdminUser as au", String.class);
return tq.getResultList();
} catch (ClassNotResolvedException | javax.persistence.PersistenceException cnre) {
// catch the exception because AppEngine DataStore has no way to create a new empty Entity table.
log.warning("AdminUser entity does not exist or is empty.");
return new java.util.ArrayList<String>();
} finally {
em.close();
}
// log.info("getAdmin(): al.size(): " + al.size());
}
public void setAdmin(java.util.List<String> admin) {
log.info("setAdmin(), admin.size():"+admin.size());
// delete all AdminUsers
com.google.appengine.api.datastore.Query query = new com.google.appengine.api.datastore.Query("AdminUser");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
java.util.List<Entity> events = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
for(Entity entity: events) {
datastoreService.delete(entity.getKey());
}
// EntityManager em = EMF.get().createEntityManager();
// Query q = em.createQuery("delete from AdminUser");
// q.executeUpdate();
// DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
for (String s: admin) {
log.info("creating AdminUser Entity...");
Entity e = new Entity("AdminUser");
e.setProperty("email", s);
datastoreService.put(e);
}
// Must wait for Datastore to actually write records. Ignores consistency even with strong consistency set.
// this doesn't even work sometimes...
//try { Thread.sleep(5000); } catch (InterruptedException e) {}
// EntityManager em = EMF.get().createEntityManager();
// for (String s: admin) {
// Entity e = new Entity("AdminUser");
// e.setProperty("email", s);
// em.persist(e);
// }
// em.close();
} // setAdmin()

Categories

Resources