How to write a HQL Insert query?

I'm struggling to write an HQL query to insert a new record into a table. I have seen some of the insert queries as shown below, but I do not want to insert data from another table as shown below.

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 User table with three fields, such as name, age, number, and I have an entity for this user table. what will be the insert request for this?

+4
source share
3 answers

HQLdoes not support this INSERT, so you need to do this by creating and saving a new object.

You can read about it here .

INSERT INTO... SELECT.... .

+2

HQL INSERT INTO... SELECT...; INSERT INTO... VALUES. HQL .

, INSERT SELECT ,

Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
                "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

secion 4

, Entity

MyEntity e=new MyEntity();
e.setXXXX(the XXX values);
save(e);
+2

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 to “not null”, or you will get a nullException.

-1
source

Source: https://habr.com/ru/post/1608019/


All Articles