I am new to the Hibernate, i want to retrieve table values from database, I have a code but it returns object values. My sample code is,
Configuration conf=new Configuration();
#SuppressWarnings("deprecation")
SessionFactory sessionfactory=conf.configure().buildSessionFactory();
Session session=sessionfactory.openSession();
List maintable = null;
try
{
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery ("select main.empid,main.address from Main as main");
maintable =q.list();
Object[] obj=maintable.toArray();
for(int i=0;i<obj.length;i++)
{
System.out.println("column valuse : "+obj[i]);
}
tx.commit();
session.close();
}
catch(Exception e1)
{
System.out.println("Exception");
}
I need to get multiple column values...How can i do that?
I can retrieve value from list easily.But in my above question i print only object property not a value.
Query qry=session.createQuery("from Main");
List<Main> user=(List<Main>) qry.list();
session.getTransaction().commit();
session.close();
for(Main u : user)
{
System.out.println("User id : "+u.getEmpid());
System.out.println("User Address:"+u.getAddress());
}
This is what Hibernate (or JPA rather) is meant for. If you want to access regular values, use JDBC instead.
It’s very useful when we retrieve some fields/properties from our entity class. The above query with “new” keyword can return a list of type “Main”. If we do not use such a keyword and specify the fields directly, a list of type Object [ ] is retrieved.
select new Main(main.empid,main.address) from Main as main ,
select main.empid,main.address from Main as main
please check that empid,address are the column name in the database or the property name of Main class.
It should be the property name of entity(i.e Main) class.
Related
I have a hibernate implementation inside my JSF2 code trying to list some records from MySQL DB. There are following code snippets: Search.java - implementing the querying logic; Student.java - implementing the record saving logic.
The problem I am facing is whenever I run Search.java, the result returned is 'null'.
Please note - my DB has already many entries and even when I tried to query Student myStudent = session.get(Student.class, 23); it returned me 'null'.
Here 23 is the id field in the SQL table. Also, the table has auto-generated PK as id. I have another class for inserting the records that works perfectly fine.
Search.java:
public class Search {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
Student tempStudent = new Student("bob", "thebuilder", "good", "blabla#bla.com", "(456)-456 5897");
session.beginTransaction();
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
System.out.println("id of the student is " + tempStudent.getId());
session = factory.getCurrentSession();
session.beginTransaction();
System.out.println("student with id " + tempStudent.getId());
Student myStudent = session.get(Student.class, tempStudent.getId());
session.getTransaction().commit();
System.out.println("Done!");
} finally {
factory.close();
}
}
}
Please advise what mistake I might have made here. I've spent hours googling. Also, please forgive me for my (possibly) rookie mistakes, I am new to Hibernate and to this website.
Let me know if I need to post error stack or my cfg.xml as well.
As I can see in your case id of tempStudent is 0. You need to get from session by id of saved student.
Try this:
Serializable id= session.save(tempStudent);
...
Student myStudent = session.get(Student.class, id);
Also you can enable show_sql property in your hibernate.cfg file. It will log all generated sql, so you can chek if it is ok.
I want to add a value to an existing column, but I don't want to have to select it first. Right now I would have to do something like
// run hql in a named query
from Employee where id = :id
// after running the above
e.setBonus(e.getBonus() + 100); // add 100 to e's bonus
// commit to database
HibernateUtil.saveOrUpdate(e);
But I want something that's just one-and-done - something like
update Employee e set e.bonus = e.bonus + 100
Is this something I can do in Hibernate? If so, how. If not, what's the suggested best practice for such an update?
You could create a hql query that just does an update
Query updateBonus = createQuery("UPDATE Employee SET bonus = bonus+100 WHERE id = :id" );
updateBonus.setInteger("id", employee.getId());
updateBonus.executeUpdate();
Yes, you can do it as intended with hql query. Try such code:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql="update Employee e set e.bonus = e.bonus + :p where id=:id";
session.createQuery(hql).setInteger("p",100).setInteger("id",id).executeUpdate();
tx.commit();
session.close();
More info you can find by the link
(source: hostingpics.net)
how can I add a new customer or supplier?, last time I was using this class for one table "customer":
Code:
public int addnewcustomer(){
int idcust;
DBConnection eConnexion = new DBConnection();
try {
//Statement state = eConnexion.getConnexion().createStatement();
String sql = "INSERT INTO customer(name_cust, num_cust, adress_cust, city_cust , tel_cust, ref_cust)";
sql+= "VALUES (?,?,?,?,?,?)";
PreparedStatement insertQuery = eConnexion.getConnexion().prepareStatement(sql);
insertQuery.setString(1,Name_cust);
insertQuery.setString(2,Num_cust);
insertQuery.setString(3,Adress_cust);
insertQuery.setString(4,City_cust );
insertQuery.setString(5,Tel_cust);
insertQuery.setString(6,Ref_cust);
insertQuery.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null,"Erreur:the addition is not performed with Succee!");
idcust = 0;
}
eConnexion.closeConnection();
idcust= Services.getLastInsertedId("customer","id_customer");
return idcust;
}
Currently, I attach all tables with new table "person". All tables now extend "person", I tried to add new customer with super variables "person" but I'm stuck in filling foreign key "id_pers FK".
First you need to persist a person into your database. After a successful(!) persist, you can query for the id the database used to insert the data. Most databases also provide a method to directly retrieve the used id after an insert.
After you have successfully persisted the person you can use the id for the foreign key column.
You may consider using a transaction for these actions, as there should never be a person persisted without a customer/employee whatever extending the persons data.
With a transaction, you can rollback the previous actions, for example if something goes wrong during the insertion of the customer.
I have a form that is connected to the database via hibernate. With this form, the user can go in and fill out fields such as names, address, and email information, etc. After they are all done filling out information they would submit the form. After submit, all the information would be display on a data table on the same page.
I am using session to interact with the database. However, the data that is being populated from database doesn't seem to be right.
public void somefunction() {
//The sessionfactory is being configured in another class
Session s = sessionFactory.openSession();
Transaction tx= null;
try {
tx= s.beginTransaction();
List userInformation = s.createQuery("FROM database1 WHERE PKEY ='"+somevalue+"'").list();
for(Iterator iterator = userInformation.iterator; iterator.hasNext();){
//database1 is an entity bean
database1 x = (database1) iterator.next();
System.out.print(x.getName());
}
tx.commit();
}
catch(Exception) {......}
finally {.....}
}
After the user submit the first "user" with their information, everything shows up in the datatable fine. However, when they enter a second "user" the row displayed on the datatable is the same information as the first user, even though the data is different. I think the code looks correct, so i am not sure what could be wrong with this.
you should use primary key to get correct value.
List userInformation = s.createQuery("FROM database1 where yourId='PK'").list();
In your query always it will return first row.
Found the solution.
Instead of using session.createQuery("QUERY"), I used
Criteria cr = session.createCriteria(SomeClass.class)
cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
cr.add(/* add some filters here */);
ScrollableResults sr = cr.scroll(ScrollMode.FORWARD_ONLY);
while(sr.next) {
someObject so = (someObject) sr.get(0);
//Do action here
}
that solved my problem of returing a single result.
I am using Hibernate and MySql.
I have a 2 tables:
User: id, name, type
City: id, name, type
type: id, name
Where user.type has foreign key to user_type.id. and as well city.
I would like before deleting a row in user_type table, to check if any row from any table is related to it.
my columns are mapped for example:
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "type_id")
How can I do it?
You said
I have around 100 tables like User and City mapped to this value
ok. Hibernate with JPA book says
You may have removed all other references manually
Which implies you should query manually any related Table. But it says if other entity references Type, database constraints prevent any inconsistency and you see a foreign key constraint exception. I Think it is the best way you can check out what you want. Otherwise, you should query manually for any related Table.
try {
userType = (Type) session.load(Type.class, id);
session.delete(userType);
/**
* or JDBCException
* e.getCause()
* e.getErrorCode() - vendor-specific
*/
} catch (HibernateException e) {
// checkout Exception right here e.getCause();
}
All exceptions thrown by Hibernate are fatal. This means you have to roll back the database transaction and close the current Session. So you may want To open a new session.
use native SQL with Hibernate together:
boolean canDeleteType(ind type_id){
Session s = HibernateUtil.getSessionFactory();
s.beginTransaction();
Query q = s.createQuery("SELECT User.type_id From User");
List l = q.list();
if(l.contains(type_id){
return false;
}
return false;
}
and do the same for your City table too.