Hibernate output name of columns - java

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

Related

Hibernate model data not saved in database

I have 5 tables data those needs to be saved at a same time into database.My code snippet is as below.
public boolean addStudentDetail(RegisterLoginDetail registerLoginDetail,
StudentRegisterBasicDetail studentRegisterBasicDetail, StudentBoardDetail studentBoardDetail,
StudentSchoolDetail studentSchoolDetail, StudentAdditionalDetail studentAdditionalDetail,
StepCompletionMatrix stepCompletionMatrix) {
boolean isSuceess = true;
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.saveOrUpdate(registerLoginDetail);
session.saveOrUpdate(studentRegisterBasicDetail);
session.saveOrUpdate(studentBoardDetail);
session.saveOrUpdate(studentSchoolDetail);
session.saveOrUpdate(studentAdditionalDetail);
session.saveOrUpdate(stepCompletionMatrix);
transaction.commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
isSuceess = false;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return isSuceess;
}
But for my two transaction data entry for insert operation not found in StudentRegisterBasicDetail table and all other table contains entry for one common id shared between each table.My webapplication is in pilot testing mode and concurrent users are making entry through form.So I am not able to figure out for which reason my entry being skipped in that table.There is no exception log for that table entry and if exception occurs then rollback for all table should be happen or not?
Please help me...

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 :)

Data doesn't retrieving with Hibernate max query

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.

Hibernate: how to query in condition from view

public List<ShoworderbybidId> queryTradesByBid(String bid) throws Exception {
Session session=null;
Transaction transaction=null;
List<ShoworderbybidId> orders=new ArrayList<ShoworderbybidId>();
try {
session=HibernateSessionFactory.getSession();
transaction=session.beginTransaction();
Query query=session.createQuery("from Showorderbybid");// In this way, I could query all results from view Showorderbybid
//Query query=session.createQuery("from Showorderbybid where bid = "+bid); //I try to use this code to find out the orders from a view(Showorderbybid) in my database. However, it failed. It said " Unknown column 'ru0001' (bid=ru0001) in 'where clause' "
orders=(List<ShoworderbybidId>)query.list();
transaction.commit();
} catch (Exception e) {
throw e;
}finally{
HibernateSessionFactory.closeSession();
}
return orders;
}
You can use criteria to create conditional query, however you can also use what you had write in your code, i think there should be problem with "bid" column, is it's name is same as in the bean? and give your error trace.

Categories

Resources