Mythul
Mythul

Reputation: 1807

Insert Sql query not working with HQL

I am trying to make a simple insert into a DB with HQlL by using native SQL code.

It doesn't give any error, it just doesn't work. Any help is appreciated.

Thanks.

public void AddMedicament(Medicament medicament) {
    System.out.println(medicament.getName());
    // open a database connection
    Session session = FarmacieHibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    // prepare SQL insert command
    session.createSQLQuery("insert into Medicament(name) values('test')");

    // close the database connection
    session.close();
}

Upvotes: 0

Views: 702

Answers (4)

sunkara suresh
sunkara suresh

Reputation: 19

session.saveOrUpdate(medicament); tx.commit(); then it will insert if u r not setting the Primarykey, if u r setting the PK in the domain object then it will be updated.

no need to executeQuery in hibernate if you are using the Spring ORM.

Upvotes: 2

Gabi Carballo
Gabi Carballo

Reputation: 67

If you use createSQLQuery this throw a native sql instruction

Your object table name is Medicament too?

Upvotes: 2

Ankit Bansal
Ankit Bansal

Reputation: 5072

You need to call

session.executeUpdate() 
transaction.commit(); 

before closing session.

Upvotes: 2

evgenyl
evgenyl

Reputation: 8107

I am not familar with Hibernate, but i dont see you sre running your command. You just create query and close session I think you need some statement to execute it.

Upvotes: 2

Related Questions