HQL和Criteria
HQL(Hibernate Query Language)
面向对象的查询语言,与SQL不同,HQL中的对象名是区分大小写的(除了JAVA类和属性其他部分不区分大小写);HQL中查的是对象而不是和表,并且支持多态;HQL主要通过Query来操作,Query的创建方式:
Query q = session.createQuery(hql);
from Person
from User user where user.name=:name
from User user where user.name=:name and user.birthday < :birthday
示例代码:
public static void query(String name){
Session s=null;
try{
s=HibernateUntils.getSession();
String hql="from User as user where user.username=?";//from Object,查找的是对象
Query query=s.createQuery(hql);
query.setString(0, name);
List<User> list=query.list();
for(User user:list){
System.out.println(user.getBirthday());
}
}finally{
if(s!=null){
s.close();
}
}
}
/**
* 确定查询结果只有一条时
* @param name
*/
public static void uniqueQuery(String name){
Session s=null;
try{
s=HibernateUntils.getSession();
String hql="from User as user where user.username=?";//from Object,查找的是对象
Query query=s.createQuery(hql);
query.setString(0, name);
User u=(User) query.uniqueResult();
System.out.println(u.getBirthday());
}finally{
if(s!=null){
s.close();
}
}
}
/**
* 分页查询
* @param name
*/
public static void queryPage(String name){
Session s=null;
try{
s=HibernateUntils.getSession();
String hql="from User as user where user.username=:name";//from Object,查找的是对象
Query query=s.createQuery(hql);
query.setString("name", name);
query.setFirstResult(0);//第一条记录从哪一条开始去
query.setMaxResults(10);//取多少条
List<User> list=query.list();
for(User user:list){
System.out.println(user.getBirthday());
}
}finally{
if(s!=null){
s.close();
}
}
}
 
Criteria
Criteria是一种比HQL更面向对象的查询方式;Criteria的创建方式:
Criteria crit = session.createCriteria(DomainClass.class);
简单属性条件如:criteria.add(Restrictions.eq(propertyName, value)),
criteria.add(Restrictions.eqProperty(propertyName,otherPropertyName))

/**
* 条件查询
* @param name
*/
public static void cri(String name){
Session s=null;
try{
s=HibernateUntils.getSession();
Criteria c=s.createCriteria(User.class);
c.add(Restrictions.eq("username", name));//加入约束条件
List<User> list=c.list();
for(User user:list){
System.out.println(user.getBirthday());
}
}finally{
if(s!=null){
s.close();
}
}
}

 小练习:

实验步骤:
1.设计domain对象User。
2.设计UserDao接口。
3.加入hibernate.jar和其依赖的包。
4.编写User.hbm.xml映射文件,可以基于hibernate/eg目录下的org/hibernate/auction/User.hbm.xml修改。
5.编写hibernate.cfg.xml配置文件,可以基于hibernate/etc/hibernate.cfg.xml修改;必须提供的几个参数:
connection.driver_class、connection.url、connection.username、connection.password、dialect、hbm2ddl.auto。
6.编写HibernateUtils类,主要用来完成Hibnerate初始化和提供一个获得Session的方法;这步可选。
7.实现UserDao接口。

源代码:
User.java   实体类

package com.dzq.domain;

import java.io.Serializable;
import java.util.Date; public class User implements Serializable{
private int id;
private String username;
private String password;
private String mobile;
private Date regdate; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getMobile() {
return mobile;
} public void setMobile(String mobile) {
this.mobile = mobile;
} public Date getRegdate() {
return regdate;
} public void setRegdate(Date regdate) {
this.regdate = regdate;
} }

  UserDao.java  接口

package com.dzq.dao;

import com.dzq.domain.User;

public interface UserDao {

	/**
* 添加用户
*
* @param user
*/
void addUser(User user); /**
* 修改用户
*
* @param user
*/
void updateUser(User user); /**
* 删除用户
*
* @param user
*/
void deleteUser(User user); /**
* 根据id查找用户
*
* @param id
*/
User findUserByID(int id); /**
* 根据id删除用户
*
* @param id
*/
void deleteUserByID(int id); /**
* 根据用户名查找用户
* @param username
*/
User findUserByUN(String username); }

  User.hbm.xml   实体配置

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dzq.domain"> <class name="User" table="user">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="username" column="username" />
<property name="password" column="password" />
<property name="mobile" column="mobile" />
<property name="regdate" column="regdate"/>
</class> </hibernate-mapping>

  

  hibernate.cfg.xml  全局配置文件

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/dzq/domain/User.hbm.xml"/>
</session-factory> </hibernate-configuration>

  HibernateUtils.java  工具类

package com.dzq.utils;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration; public class HibernateUntils {
private static SessionFactory sessionFactory; private HibernateUntils() { } static {
Configuration cfg = new Configuration();
cfg.configure();//如果不是hibernate.cfg.xml这个文件名,需要加上文件名
sessionFactory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
return sessionFactory.openSession();
} /**
* 添加
* @param entity
*/
public static void add(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUntils.getSession();
tx = s.beginTransaction();
s.save(entity);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException(e);
} finally {
if (s != null) {
s.close();
}
}
}
/**
* 修改
* @param entity
*/
public static void update(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUntils.getSession();
tx = s.beginTransaction();
s.update(entity);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException(e);
} finally {
if (s != null) {
s.close();
}
}
} /**
* 删除
* @param entity
*/
public static void delete(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUntils.getSession();
tx = s.beginTransaction();
s.delete(entity);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException(e);
} finally {
if (s != null) {
s.close();
}
}
} /**
* 根据主键id查询
* @param clazz
* @param id
* @return
*/
public static Object get(Class clazz,Serializable id) {
Session s = null;
try {
s = HibernateUntils.getSession();
Object obj=s.get(clazz, id);
return obj;
} finally {
if (s != null) {
s.close();
}
}
}
}

  


UserDaoImpl.java    接口实现

package com.dzq.dao.impl;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.dzq.dao.UserDao;
import com.dzq.domain.User;
import com.dzq.utils.HibernateUntils; public class UserDaoImpl implements UserDao { @Override
public void addUser(User user) {
HibernateUntils.add(user);
} @Override
public void updateUser(User user) {
HibernateUntils.update(user);
} @Override
public void deleteUser(User user) {
HibernateUntils.delete(user);
} @Override
public User findUserByID(int id) {
return (User) HibernateUntils.get(User.class, id);
} @Override
public void deleteUserByID(int id) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUntils.getSession();
tx = s.beginTransaction();
String hql="delete User user where user.id=:id";
Query query=s.createQuery(hql);
query.setInteger("id", id);
query.executeUpdate();
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException(e);
} finally {
if (s != null) {
s.close();
}
}
} @Override
public User findUserByUN(String username) {
Session s=null;
try{
s=HibernateUntils.getSession();
String hql="from User as user where user.username=:username";//from Object,查找的是对象
Query query=s.createQuery(hql);
query.setString("username", username);
User user=(User) query.uniqueResult();
return user;
}finally{
if(s!=null){
s.close();
}
}
} }

  ProjectTest.java   下面为junit测试

package com.dzq.test;

import java.util.Date;

import org.junit.Test;

import com.dzq.dao.impl.UserDaoImpl;
import com.dzq.domain.User; public class ProjectTest {
@Test
public void testAdd() {
UserDaoImpl dao = new UserDaoImpl();
User user = new User();
user.setUsername("xiaodu");
user.setPassword("hello");
user.setRegdate(new Date());
user.setMobile("15820090820");
dao.addUser(user);
} @Test
public void testUpdate() {
UserDaoImpl dao = new UserDaoImpl();
User user = new User();
user = dao.findUserByID(2);
user.setUsername("xiaohong");
dao.updateUser(user);
} @Test
public void testDelete(){
UserDaoImpl dao = new UserDaoImpl();
User user = new User();
user = dao.findUserByID(3);
dao.deleteUser(user);
}
@Test
public void testFindUser(){
UserDaoImpl dao = new UserDaoImpl();
User user = new User();
user=dao.findUserByUN("xiaohong");
System.out.println(user.getRegdate());
}
@Test
public void testDeleteByID(){
UserDaoImpl dao = new UserDaoImpl();
dao.deleteUserByID(2);
} }

  

20160506-hibernate入门的更多相关文章

  1. 三大框架之hibernate入门

    hibernate入门   1.orm      hibernate是一个经典的开源的orm[数据访问中间件]框架           ORM( Object Relation Mapping)对象关 ...

  2. Hibernate入门案例及增删改查

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  3. Hibernate入门案例 增删改

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  4. Hibernate入门6.Hibernate检索方式

    Hibernate入门6.Hibernate检索方式 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv Hibernate的整体框架已经 ...

  5. Hibernate入门5持久化对象关系和批量处理技术

    Hibernate入门5持久化对象关系和批量处理技术 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv 前言: 前面学习了Hiberna ...

  6. Hibernate入门4.核心技能

    Hibernate入门4.核心技能 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv 前言: 前面学习了Hibernate3的基本知识, ...

  7. Hibernate入门3.配置映射文件深入

    Hibernate入门3.配置映射文件深入 2013.11.27 前言: 之前的两节是在Java项目中如何使用hibernate,并且通过一个简单地项目实践,期间有很多的错误,一般都是因为配置包的问题 ...

  8. 简单的Hibernate入门简介

    其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...

  9. Hibernate入门(1)-第一个Hibernate程序

    Hibernate入门(1)-第一个Hibernate程序 Hibernate是最著名的ORM工具之一,本系列文章主要学习Hibernate的用法,不涉及Hibernate的原理.本文介绍第一个Hib ...

  10. hibernate入门之person表

    下面的hibernate入门person表指的是:根据mysql数据库中的test表和其中的元素-->建立映射表==>进而创建持久化类的顺序来操作了,下面为步骤 1.配置MySQL驱动程序 ...

随机推荐

  1. HW7.10

    public class Solution { public static void main(String[] args) { int[][] array = new int[3][3]; for( ...

  2. 【转】hive简介安装 配置常见问题和例子

    原文来自:  http://blog.csdn.net/zhumin726/article/details/8027802 1 HIVE概述 Hive是基于Hadoop的一个数据仓库工具,可以将结构化 ...

  3. Google Android官方文档进程与线程(Processes and Threads)翻译

    android的多线程在开发中已经有使用过了,想再系统地学习一下,找到了android的官方文档,介绍进程与线程的介绍,试着翻译一下. 原文地址:http://developer.android.co ...

  4. 异步网页采集利器CasperJs

    在采集网页中,我们会经常遇到采集一些异步加载页面的网页,我们通常用的httpwebrequest类就采集不到了,这个时候我们通常会采用webbrowser来辅助采集,但是.net下自带的webbrow ...

  5. 用EPOLL进行压力测试

    在以前的博客中提到的一个服务端,在以前压力测试的过程中,发现单核CPU最多能达到1000TPS 还以为是服务端性能不够好,所以一直想着怎么去优化它. 但优化的思路明显不多,所以就考虑换一种压力测试的方 ...

  6. 测试JS基本类型以及对象的引用

    自己敲的. 1 <script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js&qu ...

  7. 针对 .NET 框架的安全编码指南

      此主题尚未评级 - 评价此主题 发布日期 : 10/9/2004 | 更新日期 : 10/9/2004 Microsoft Corporation 适用于: Microsoft .NET 框架 摘 ...

  8. JavaScript要点 (一) 变量-作用域

    JavaScript 作用域 作用域—可访问变量的集合. 全局变量或者函数可以覆盖window对象的变量或者函数: 局部变量和window对象可以覆盖全局变量和函数. JavaScript 作用域 在 ...

  9. 秀一套每秒处理1500+个事务的profile

    秀一套每秒处理1500+个事务的profile,真实生产环境

  10. 如何用 iptables 禁止某个ip?

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...