hibernate简单事例,注意事项,保存,更新,删除,session,Query,Criteria查询_Hql与Criteria查询的补充知识

作者: dwt1220
发布时间:2015-07-08 18:29:35

 

需要jar包

简单事例 

注意事项


保存,更新,删除

查询

session.get(id);


Query接口查询

query.list();

query.uniquResult();


Criteria接口查询

criteria.list();

criteria.uniqueResult();

 

Hql与Criteria查询的补充知识

 


 需要jar包

mysql jar包:http://www.mysql.com/downloads/connector/j/ 

hibernate jar包:http://sourceforge.net/projects/hibernate/files/hibernate3/3.2.5.ga/

 

当前使用版本3 .2.5

 

简单事例 一、User类

      

package com.dwt1220;    import java.util.Date;    public class User {  	private String userName;  	private Date birthday;  	private int id;    	public String getUserName() {  		return userName;  	}    	public void setUserName(String userName) {  		this.userName = userName;  	}    	public Date getBirthday() {  		return birthday;  	}    	public void setBirthday(Date birthday) {  		this.birthday = birthday;  	}    	public int getId() {  		return id;  	}    	public void setId(int id) {  		this.id = id;  	}    }  


二、User的配置文件(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.dwt1220">  <!-- 	<class name="User" table"user"> table 属性可选(类对应的表名),如果表名和字段名是数据库的关节字,可以加''-->  	<class name="User">  		<id name="id">  			<generator class="native"/>  		</id>  		<!-- column可选(类属性对应的字段) 	<property name="userName" column="username"/>-->  		<property name="userName"/>  		<property name="birthday"/>  	  	</class>  	  </hibernate-mapping>  

如果表名和字段名是数据库的关节字,可以加‘’
 

三、hibernate的配置文件(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:///test</property>  		<property name="hibernate.connection.username">root</property>  		<property name="hibernate.connection.password">123</property>  		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>  		<property name="hbm2ddl.auto">create</property>  		  		<mapping resource="com/dwt1220/User.hbm.xml"/>   	</session-factory>  </hibernate-configuration>

 默认目录

src/ hibernate-configuration.xml,可使用configuration.configure("路径");来改变

hibernate-configuration.xml与hibernate.properties同时存在时,xml优先

所有属性与值可在hibernate.properties中找到

必填字段

 connection.driver_class

 connection.url

 connection.username

 connection.password,

 dialect

建表的必填字段

hbm2ddl.auto

 



四 Test类(main)

package com.dwt1220;    import java.util.Date;      import org.hibernate.HibernateException;  import org.hibernate.Session;  import org.hibernate.Transaction;    public class Test {    	public static void main(String[] args) {  		User user = new User();  		user.setUserName("name123");  		user.setBirthday(new Date());    		addUser(user);    		System.out.println("end");  	}    	static void addUser(User user) {  		Session session = null;  		Transaction tx = null;  		try {  			session = HibernateUtil.getSession();  			tx = session.beginTransaction();  			session.save(user);  			tx.commit();  		} catch (HibernateException e) {  			if (tx != null) {  				tx.rollback();  			}  			throw e;  		} finally {  			if (session != null) {  				session.close();  			}  		}  	}    	static void addUser1(User user) {  		Session session = null;  		Transaction tx = null;  		try {  			session = HibernateUtil.getSession();  			tx = session.beginTransaction();  			session.save(user);  			tx.commit();  			// 不catch,出错会自动回滚  		} finally {  			if (session != null) {  				session.close();  			}  		}  	}    }




 五、工具类(HibernateUtil)

package com.dwt1220;    import org.hibernate.Session;  import org.hibernate.SessionFactory;  import org.hibernate.cfg.Configuration;    public final class HibernateUtil {  	private static Session session;  	private static SessionFactory sessionFactory;    	private HibernateUtil() {  		super();  	}    	static {  		Configuration configuration = new Configuration();  		configuration.configure();  		sessionFactory = configuration.buildSessionFactory();  	}    	public static Session getSession() {  		session = sessionFactory.openSession();  		return session;  	}    	public static SessionFactory getSessionFactory() {  		return sessionFactory;  	}  }  


 


 

注意事项

 1、默认的构造方法(必须的)

 2、有无意义的标识符id(主键) 可选

 3、非final的,对加载有影响 可选


保存,更新,删除

public void addUpdateDelete(User user) {  		Session session = null;  		Transaction tx = null;  		try {  			session = HibernateUtil.getSession();  			tx = session.beginTransaction();  			session.save(user);  			session.update(user);  			session.delete(user);  			session.saveOrUpdate(user);//不确定是更新还是保存时;  			tx.commit();  		} catch (HibernateException e) {  			if (tx != null) {  				tx.rollback();  			}  			throw e;  		} finally {  			if (session != null) {  				session.close();  			}  		}  	}


查询

session.get(id);

public User getUser(int id){  		Session session = null;  		User user=new User();  		try {  			session = HibernateUtil.getSession();		  			user=(User)session.get(User.class, id);  		} finally {  			if (session != null) {  				session.close();  			}  		}  		return user;  	}


Query接口查询

query.list();

query.uniquResult();

	public static List<User> select(String val){  		Session session=HibernateUtil.getSession();  		List<User> list;  		try{  		String queryString="from User as user where user.userName=:n";//:n字符串中的别名  		Query query=session.createQuery(queryString);  		query.setString("n",val);//替代:n的值  		/**返回一个结果集*/  		list=query.list();  		/**以对象方式,只返回一个结果*/  		User user=(User)query.uniqueResult();//返回一条查询结果,如果查询结果为多条。则报错  		}finally{  		session.close();  		}  		return list;  	}


Criteria接口查询

criteria.list();

criteria.uniqueResult();

	public User findUser(String name) {  		Session session = HibernateUtil.getSession();  		User user = null;  		try {  			Criteria criteria = session.createCriteria(User.class);  			criteria.add(Restrictions.eq("userName", name));  			List<User> userList=criteria.list();  			user = (User) criteria.uniqueResult();  		} finally {  			if (session != null) {  				session.close();  			}  		}  		return user;  	}

Restrictions.ge("greater than or equal",name);  大于等于

Restrictions.gt("greater than",name); 大于

Restrictions.le("less than or equal", name); 小于等于

Restrictions.lt("less than", name); 小于

查询

session.get(id);

 

Hql与Criteria查询的补充知识

HQL

  1查询多个对象select art, user from Article art, User user where art.author.id=user.id and art.id=:id这种方式返回的是Object[],Object[0]:article,Object[1]:user。

  2分页query.setFirstResult,query.setMaxResults.

    查询记录总数query.iterate(“select count(*) from Person”).next()

  3批量更新query.executeUpdate()可能造成二级缓存有实效数据。

 

 

Criteria

  1排序Criteria.addOrder(Order.desc(propertyName));

  2关联查询criteria.setFetchMode(“propertyName”, FetchMode.SELECT)与映射文件中关联关系的fetch作用一致。

  3投影Projections.rowCount(),max(propertyName), avg, groupProperty…

  4分页Projections.rowCount(),criteria.setFirstResult(),criteria.setMaxResults()

  5DetachedCriteria可在session外创建(在其他层创建比如在Service中创建)然后用getExecutableCriteria(session)方法创建Criteria对象来完成查询。

  6Example查询,Example.create(obj);criteria.add(example)。

 

5、DetachedCriteria事例

package com.dwt1220;    import java.util.Date;  import java.util.List;    import org.hibernate.Criteria;  import org.hibernate.HibernateException;  import org.hibernate.Session;  import org.hibernate.Transaction;  import org.hibernate.criterion.DetachedCriteria;  import org.hibernate.criterion.Restrictions;    public class Test {    	public static void main(String[] args) {  		User user = new User();  		user.setUserName("name123");  		user.setBirthday(new Date());    		addUser(user);  		  		DetachedCriteria detachedCriteria=DetachedCriteria.forClass(User.class);  		String name="name";  		detachedCriteria.add(Restrictions.eq("name", name));    		System.out.println("end");  	}    	static void addUser(User user) {  		Session session = null;  		Transaction tx = null;  		try {  			session = HibernateUtil.getSession();  			tx = session.beginTransaction();  			session.save(user);  			tx.commit();  		} catch (HibernateException e) {  			if (tx != null) {  				tx.rollback();  			}  			throw e;  		} finally {  			if (session != null) {  				session.close();  			}  		}  	}  	  	static List detachedCriteria(DetachedCriteria detachedCriteria){  		Session session=HibernateUtil.getSession();  		Criteria criteria=detachedCriteria.getExecutableCriteria(session);  		List rs=criteria.list();  		session.close();  		return rs;  		  	}    }  

版权声明:本文为博主原创文章,未经博主允许不得转载。

来源:http://blog.csdn.net/dwt1220/article/details/7226770

推荐: