力所能及之hibernate简单的增删查改

来源:互联网 发布:建筑工程造价软件 编辑:程序博客网 时间:2024/06/15 06:42

小狼今天在Hibernate相关的东西,就来说说hibernate最简单的增删查改吧

同样,写一个hibernate.cfg.xml   小狼在这里用mysql,oracle实在太慢,大家见谅

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE  hibernate-configuration            PUBLIC  "-//Hibernate/Hibernate  Configuration  DTD//EN"            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  <hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/zhang</property><property name="connection.username">root</property><property name="connection.password">root</property><!-- JDBC connection pool (use the built-in) --><property name="connection.pool_size">2</property><!-- SQL dialect --><property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property><!-- Enable Hibernate's current session context --><property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property><!-- Disable the second-level cache  --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><!-- Drop and re-create the database schema on startup --><property name="hbm2ddl.auto">update</property><mapping resource="qh/zcy/entity/User.hbm.xml"></mapping></session-factory></hibernate-configuration>
大家看这里

<property name="hbm2ddl.auto">update</property>
这个地方的值是有说法的,大家注意了

大家看这行

<mapping resource="qh/zcy/entity/User.hbm.xml"></mapping>

毋庸置疑,下面我们来创建User.hbm.xml

<hibernate-mapping package="org.hibernate.test.hql">
package表明映射文件对应的实体类所在的包路径,加了它
可以省去每个class都要写全name,如果不写这一项则
<class …>中的name=”User” 则要在User之前加上具体的包路径:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <class name="qh.zcy.entity.User" table="t_user">        <id name="id" column="ID" type="int">            <generator class="increment"/>        </id>        <property name="name" type="string"/>           </class></hibernate-mapping>

很简单的一个表,Javabean小狼在这里就不说了

看看DaoTest,这里使用junit4测试

 package qh.zcy.dao;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.junit.Test;import qh.ConstantUtil;import qh.HibernateSessionFactory;import qh.Log;import qh.zcy.entity.User;public class UserDao {    //save方法@Testpublic void TestUserAdd() {ConstantUtil.session = null;ConstantUtil.transaction = null;try {ConstantUtil.session = HibernateSessionFactory.getSessionFactory().openSession();ConstantUtil.transaction = ConstantUtil.session.beginTransaction();User user = new User();user.setName("zhang");ConstantUtil.session.save(user);ConstantUtil.transaction.commit();} catch (HibernateException e) {// TODO Auto-generated catch blocke.printStackTrace();ConstantUtil.transaction.rollback();}finally{ConstantUtil.session.close();}}    //修改方法//运行这个方法的时候hibernate.cfg.xml中<property name="hbm2ddl.auto">update</property>选项一定要是update//否则报org.hibernate.StaleStateException错误,这个小狼在前面主要讲过@Testpublic void TestUserUpdate() {ConstantUtil.session = null;ConstantUtil.transaction = null;try {ConstantUtil.session = HibernateSessionFactory.getSessionFactory().openSession();ConstantUtil.transaction = ConstantUtil.session.beginTransaction();User user = new User();user.setId(1);user.setName("chouchou");ConstantUtil.session.update(user);ConstantUtil.transaction.commit();} catch (HibernateException e) {// TODO Auto-generated catch blocke.printStackTrace();ConstantUtil.transaction.rollback();}finally{ConstantUtil.session.close();}}//删除方法@Testpublic void TestUserDelete() {ConstantUtil.session=HibernateSessionFactory.getSessionFactory().openSession();ConstantUtil.transaction=ConstantUtil.session.beginTransaction();User user=new User();user.setId(1);ConstantUtil.session.delete(user);ConstantUtil.transaction.commit();ConstantUtil.session.close();}//查询方法  查询t_user表中的所有数据//这里的(from User)是hibernate的hql语句,具体的大家可以查阅资料@SuppressWarnings("unchecked")@Testpublic void TestUserFindAll() {ConstantUtil.session=HibernateSessionFactory.getSessionFactory().openSession();//ConstantUtil.transaction=ConstantUtil.session.beginTransaction();Query query=ConstantUtil.session.createQuery("from User");List<User> lists=query.list();for(User user:lists){Log.getLog().info("id="+user.getId()+"   name="+user.getName());}ConstantUtil.session.close();}    //通过id查询该行数据方法一:通过数值查询@Testpublic void TestUserFindById_1() {ConstantUtil.session=HibernateSessionFactory.getSessionFactory().openSession();//ConstantUtil.transaction=ConstantUtil.session.beginTransaction();User user=(User)ConstantUtil.session.get(User.class, 1);Log.getLog().info("id="+user.getId()+"    name="+user.getName());ConstantUtil.session.close();}    //通过id查询该行数据方法一:通过字符串查询@Testpublic void TestUserFindById_2() {ConstantUtil.session=HibernateSessionFactory.getSessionFactory().openSession();//ConstantUtil.transaction=ConstantUtil.session.beginTransaction();Query query=ConstantUtil.session.createQuery("from User u where name=?");User user=(User)query.setString(0, "zhang").uniqueResult();Log.getLog().info("id="+user.getId()+"    name="+user.getName());ConstantUtil.session.close();}}



大家测试一下,这些小狼都测试过,完全没有问题


0 0