Hibernate 中update hql语句

今天在MySQL中用hibernate测试update语句发现以下问题:

update语句竟然不去作用;

表机构如下:

create table student
(sid int primary key ,
sname varchar(45) not null,
ssex char(2) not null,
sdept varchar(10) not null,
sage int ,
saddress varchar(45)
);

update语句如下:

String[] params = new String[] { "20", "成龙" };

HibernateUtil.executeUpdate(
"update Student s set s.sage=? where s.sname=?",params);

package com.huml.util;

import java.util.ArrayList;
import java.util.Arrays;

import org.hibernate.Transaction;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sf;
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    static {
        sf = new Configuration().configure().buildSessionFactory();
    }

    private HibernateUtil() {

    }

    public static Session openSession() {
        return sf.openSession();
    }

    public static Session getcurrentSession() {
        Session session = threadLocal.get();

        if (session == null) {
            session = sf.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    public static void save(Object obj) {
        Session session = openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            session.save(obj);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static ArrayList executeQuery(String hql, String... params) {
        Session session = openSession();
        Transaction tx = null;
        ArrayList list = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery(hql);

            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    query.setParameter(i, params[i]);
                }
            }
            list = (ArrayList) query.list();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return list;
    }

    public static void executeUpdate(String hql, String... params) {

        Session session = openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            Query query = session.createQuery(hql);

            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    query.setParameter(i, params[i]);
                    // System.out.println("query influenced: "+params[i]);
                }
            }
            System.out.println("query influenced: " + query.getQueryString());
            int n = query.executeUpdate();
            System.out.println("query influence: " + n);
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

}

原因是MySQL中不能自动把String类型转换成Integer,在Oracle中可以修改代码如下:

Object[] params = new Object[] { 20, "成龙" };

HibernateUtil.executeUpdate(
"update Student s set s.sage=? where s.sname=?",params);

package com.huml.util;

import java.util.ArrayList;
import java.util.Arrays;

import org.hibernate.Transaction;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sf;
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    static {
        sf = new Configuration().configure().buildSessionFactory();
    }

    private HibernateUtil() {

    }

    public static Session openSession() {
        return sf.openSession();
    }

    public static Session getcurrentSession() {
        Session session = threadLocal.get();

        if (session == null) {
            session = sf.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    public static void save(Object obj) {
        Session session = openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            session.save(obj);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static ArrayList executeQuery(String hql, String... params) {
        Session session = openSession();
        Transaction tx = null;
        ArrayList list = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery(hql);

            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    query.setParameter(i, params[i]);
                }
            }
            list = (ArrayList) query.list();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return list;
    }

    public static void executeUpdate(String hql, Object... params) {

        Session session = openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            Query query = session.createQuery(hql);

            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    query.setParameter(i, params[i]);
                    // System.out.println("query influenced: "+params[i]);
                }
            }
            System.out.println("query influenced: " + query.getQueryString());
            int n = query.executeUpdate();
            System.out.println("query influence: " + n);
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }
}

这样就成功了;

Hibernate 中update hql语句

时间: 2024-10-13 05:57:07

Hibernate 中update hql语句的相关文章

hibernate中执行hql语句创建session需要的HibernateUtil类

import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory = null; static { try { Confi

使用SQLQuery 在Hibernate中使用sql语句

session.createSQLQuery.转载 对原生SQL查询执行的控制是通过SQLQuery接口进行的,通过执行Session.createSQLQuery()获取这个接口.下面来描述如何使用这个API进行查询. 1.标量查询(Scalar queries) 最基本的SQL查询就是获得一个标量(数值)的列表. sess.createSQLQuery("SELECT * FROM CATS").list();sess.createSQLQuery("SELECT ID,

hibernate中使用sql语句进行表链接查询,对结果集的遍历方法

今天做了一个在hibernate中使用sql语句进行表链接查询的功能,得到的属性是来自两个表中的字段.下面对结果集遍历的方法进行记录. sql语句不写了.部分代码如下: List<Course_Material> list = new ArrayList<Course_Material>(); @SuppressWarnings("rawtypes") List accountList = query.list(); if(accountList.size()&

hibernate中update与saveOrUpdate的区别

[转]hibernate中update与saveOrUpdate的区别 分类: Hibernate总结 2009-11-17 00:04 2121人阅读 评论(0) 收藏 举报 hibernatesession数据库javadaoapplication 先来点概念: 在Hibernate中,最核心的概念就是对PO的状态管理.一个PO有三种状态: 1.未被持久化的VO 此时就是一个内存对象VO,由JVM管理生命周期 2.已被持久化的PO,并且在Session生命周期内 此时映射数据库数据,由数据库

【SSH】Hibernate:常用的HQL语句

Hibernate query language 简称HQL,是实际开发中最长的hibernate查询封装模式. HQL提供了更加接近传统SQL语句的查询方法: <span style="font-family:Verdana;font-size:14px;">[select/update/delete-] [from-][where-][groupby-] [having -][order by-]</span> 实体查询: <span style=&q

Hibernate中的HQL查询与缓存机制

HQL:完全面向对象查询 SQL的执行顺序: 1.From 2.Where 过滤基础数据 where与having的区别:1.顺序不同 2.where过滤基础数据 3. 过滤聚合函数 3.Group by 4.Select 5.Having 6.Order by   使用Hibernate查询时,使用hibernate的一个接口query Hql是面向对象的查询语句,所以跟的是类名 Query query = session.createQuery("select id,name,stu.cla

hibernate中的sql语句

hibernate的hql查询语句总结 在这里通过定义了三个类,Special.Classroom.Student来做测试,Special与Classroom是一对多,Classroom与Student是一对多的关系,这里仅仅贴出这三个bean的属性代码: Special类: public class Special { private int id; private String name; private String type; private Set<Classroom> rooms;

Hibernate入门(六)---------HQL语句

Query: 代表面向对象的一个Hibernate查询操作.在Hibernate中,通常使用session.createQuery()方法接收一个HQL语句,然后调用Query的 list()或uniqueResult()方法执行查询.所谓的HQL是Hibernate Query Language缩写,其语法很像SQL,但它是完全面向对象的. 在Hibernate中使用Query对象的步骤,具体: 1.获得Hibernate的Session对象 2.编写HQL语句 3.调用session.cre

hibernate中使用HQL进行数据库查询

1.写的规则比较简单,我讲一下,如图Station这个不是数据库中的表,而是entity包中的类名Station,可以省略 select * 2.返回的类型自动转化为String类型,不用你自己再转化. 3.原生数据库返回的是object,需要进行转化 备注: