myeclipse中的一个hibernate实例

本文通过一个具体的Hibernate实践案例,详细介绍了如何使用Hibernate进行增删改查等基本操作,并演示了命名查询、模糊查询及HQL查询等多种查询方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是pojo类person.java:

 

package  org.jie.hibernate;

public   class  person  {

    
private String id;
    
private String name;
    
private String password;
    
private String sex;
    
private String email;
    
    
public person(String name,String sex)
    
{
        System.out.println(name
+""+sex);
    }

    
public String getId() {
        
return id;
    }

    
public void setId(String id) {
        
this.id = id;
    }

    
public String getName() {
        
return name;
    }

    
public void setName(String name) {
        
this.name = name;
    }

    
public String getPassword() {
        
return password;
    }

    
public void setPassword(String password) {
        
this.password = password;
    }

    
public String getSex() {
        
return sex;
    }

    
public void setSex(String sex) {
        
this.sex = sex;
    }

    
public String getEmail() {
        
return email;
    }

    
public void setEmail(String email) {
        
this.email = email;
    }

    
    
}

 接着是映射文件person.hbm.xml:

 

<? xml version="1.0" encoding="utf-8" ?>
<! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!--  
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
< hibernate-mapping >
    
< class  name ="org.jie.hibernate.person"  table ="person"  schema ="public" >
        
< id  name ="id"  type ="java.lang.String" >
            
< column  name ="id"  length ="20"   />
            
< generator  class ="assigned" ></ generator >
        
</ id >
        
< property  name ="name"  type ="java.lang.String" >
            
< column  name ="name"  length ="12"  not-null ="true"   />
        
</ property >
        
< property  name ="password"  type ="java.lang.String" >
            
< column  name ="password"  length ="25"  not-null ="true"   />
        
</ property >
        
< property  name ="sex"  type ="java.lang.String" >
            
< column  name ="sex"  length ="20"  not-null ="true"   />
        
</ property >
        
< property  name ="email"  type ="java.lang.String" >
            
< column  name ="email"  length ="20"  not-null ="true"   />
        
</ property >
        
    
</ class >
    
<!--  命名查询语句定义的位置是要在class之后的!  -->
    
< query  name ="person.byId" >
          
<![CDATA[ from person where id=? ]]>
        
</ query >
</ hibernate-mapping >

 

还有的就是一个定义方法的类PersonOperate.java:

 

package  org.jie.hibernate;

import  java.util.Iterator;
import  java.util.List;

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

    
public   class  PersonOperate  {
        
// 在Hibernate中,所有的操作都是通过Session完成
        
// 此Session不同于JSP的Session
        private Session session = null ;
        
        
// 在构造方法之中实例化session对象
        public PersonOperate()
        
{
            
// 找到Hibernate配置
            Configuration config = new Configuration().configure() ;
            
// 从配置中取出SessionFactory
            SessionFactory factory = config.buildSessionFactory() ;
            
// 从SessionFactory中取出一个Session
            this.session = factory.openSession() ;
        }

        
        
// 所有的操作都是通过session进行的
        
// 向数据库中增加数据
        public void insert(person p)
        
{
            
// 开始事务
            Transaction tran = this.session.beginTransaction() ;
            
// 执行语句
            this.session.save(p) ;
            
// 提交事务
            tran.commit() ;
            
// 关闭Session
            this.session.close() ;
        }

        
        
public void update(person p)
        
{
            Transaction tran
=session.beginTransaction();
            session.update(p);
            tran.commit();
            session.close();
        }

        
        
public void queryById(String id)
        
{
            person p
=null;
            
//String hql="from person where id=?";
            
//Query q=session.createQuery(hql);
            Query q=session.getNamedQuery("person.byId");  //这里采用的是命名查询的方式来进行查询的,还有的就是要注意命名查询在xml文件中定义时的位置!
            q.setString(0, id);
            List list
=q.list();
            Iterator iter
=list.iterator();
            
if(iter.hasNext())
            
{
                p
=(person)iter.next();
                System.out.println(p.getName());
            }

            
//return p;
        }

        
        
//这是Hibernate 2 下用的删除的方法,效率不高!
        
//它传入的是一个对象,而且要删除这个对象前还要通过查询先找到它先!
        public void delete(person p)
        
{
            Transaction tran
=session.beginTransaction();
            session.delete(p);
            tran.commit();
            session.close();
        }

        
        
        
//这是在Hibernate 3 下用查询语句来查询的情况
        public void delete2(String id)
        
{
            String hql
="delete person where id=?";
            Query q
=session.createQuery(hql);
            q.setString(
0, id);  //
            q.executeUpdate();
            session.beginTransaction().commit();  
//删除和更新一样,只要是有改变到数据表的操作都应该进行事务提交,否则结果不会改变!
        }

        
        
//查询全部记录
        public List queryAll()
        
{
            String hql
="from person";
            Query q
=session.createQuery(hql);
            
//q.setMaxResults(3);  //设置输出来的最大的记录的条数为3
            List l=q.list();
            
return l;
        }

        
        
//模糊查询
        public List queryByLike(String str)
        
{
            String hql
="from person as p where p.name like :str";  //采用的是命名参数的方法来进行查询,而且该参数前面的那个冒号是不能去掉的,去掉的话就会出现异常!
            Query q=session.createQuery(hql);
            q.setString(
"str""%"+str+"%");  //
            List l=q.list();
            
return l;
        }

        
        
public void myQuery()
        
{
            String hql
="select p.name, p.sex from person p";
            Query q
=session.createQuery(hql);
            List list
=q.list();
            Iterator iter
=list.iterator();
            
while(iter.hasNext())
            
{
                Object[] row
=(Object[])iter.next();  //查询后返回的列表中,每个元素都是一个包含指定值的Object[]数组。Object[]数组的长度等于检索的列数.
                String str1=(String)row[0];
                String str2
=(String)row[1];
                
                System.out.println(str1
+""+str2);
            }

        }

        
        
public void myQuery2()
        
{
            String hql
="select new person(p.name,p.sex) from person p";  //select语句可以用来创建新对象,这些对象是使用查询中的值来填充的。
            Query q=session.createQuery(hql);                            //该HQL语句使用了构造函数,这要求在原类中必须要有一个与HQL语句中使用的构造函数匹配的构造函数person()。
            List list=q.list();
            Iterator iter
=list.iterator();
            
while(iter.hasNext())
            
{
                iter.next();
            }

        }

        
        
public void myQuery3()
        
{
            String hql
="select count(p) from person p";
            Query q
=session.createQuery(hql);
            List list
=q.list();
            Iterator iter
=list.iterator();
            
while(iter.hasNext())
            
{
                System.out.println(iter.next());
            }

        }

    }

接着自然少不了调用它的主类了:TestOP.java

 (这是网上的一段视频教程,通俗易懂:http://www.ku6.com/show/KWrp8YHcvsnn3mb0.html)

package  org.jie.hibernate;

import  java.util. * ;

import  org.jie.hibernate.person;

public   class  TestPO  {

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub

        
/*person p = new person() ;
        p.setId("LXH4") ;
        p.setName("李兴华") ;
        p.setPassword("www.mldn.cn") ;
        p.setSex("男") ;
        p.setEmail("mldnqa@163.com") ;
*/

        
        PersonOperate po 
= new PersonOperate() ;
        
//po.insert(p);
        
//List list=po.queryAll();
        
//List list=po.queryByLike("2");
        
//po.queryById("LXH");
        
//Iterator iter=list.iterator();
        
//while(iter.hasNext())
        
//{
            
//p=(person)iter.next();
            
//System.out.println(p.getName());
        
//}
        po.myQuery3();
        
//po.update(p) ;
        
//person p=po.queryById("LXH");
        
//po.delete2("LXH2");
    }


}

 

最后是配置文件hibernate.cfg.xml

 

<? xml version='1.0' encoding='UTF-8' ?>
<! DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
>

<!--  Generated by MyEclipse Hibernate Tools.                    -->
< hibernate-configuration >

< session-factory >
    
< property  name ="myeclipse.connection.profile" >
        org.postgresql.Driver
    
</ property >
    
< property  name ="connection.url" >
        jdbc:postgresql://localhost:5432/testDatabase
    
</ property >
    
< property  name ="connection.username" > scnujie </ property >
    
< property  name ="connection.password" > 123456 </ property >
    
< property  name ="connection.driver_class" >
        org.postgresql.Driver
    
</ property >
    
< property  name ="dialect" > org.hibernate.dialect.PostgreSQLDialect </ property >
    
< property  name ="show_sql" > true </ property >
    
< mapping  resource ="./person.hbm.xml"   />

</ session-factory >

</ hibernate-configuration >

      以上的相关内容是我看了李兴华老师的视频教程和看hibernate quikly中文版后做的一个实践,所以在此鸣谢一下李兴华老师和书的作者先!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值