Reputation: 2602
I am struggling to write a HQL query for inserting a new record in a table. I have seen some of insert query as below but I don't want insert data from another table as below code.
String hql = "INSERT INTO Employee(firstName, lastName, salary)" +
"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
For example I have a table "User" with three fields like name, age, number and I have entity for this user table. what will be the insert query for this?
Upvotes: 12
Views: 71404
Reputation: 1
HQL supports only the INSERT INTO……… SELECT……… ; there is no chance to write INSERT INTO………..VALUES, i mean while writing the insert query, we need to select values from other table, we can’t insert our own values manually.
Upvotes: -1
Reputation: 1562
You can do:
Foo foo = new Foo(any, columns, you, want);
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(foo); //Here you have the magic
session.getTransaction().commit();
session.close();
Just make sure you add all the values set as "not null", or you´ll get a nullException.
Upvotes: 4
Reputation: 57421
In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table.
So query INSERT from SELECT is possible like this
Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
"select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();
Got from here secion 4
If you have values and Entity just call
MyEntity e=new MyEntity();
e.setXXXX(the XXX values);
save(e);
Upvotes: 12