yxhxj2006

常用链接

统计

最新评论

Hibernate实现CRUD操作

    
    最近学习hibernate有几天了,基本学会简单的增删改查,现在就把实现分享如下:

    一: 首先需要建立数据库,而我采用的mysql数据库,为了更详细hibernate的映射,我把数据库表名和字段名与实体类的类名与属性名取得不一致。
           create table t_teacher(
                id 
int auto_increment,
                t_username varchar(
50),
                t_age 
int,
                primary key(id)
          );


    二:建立数据源连接:hibernate.cfg.xml
     
<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

        
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        
"http://www.hibernate.org/dtd/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/hxj</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">1</property> --> 

 

        
<!-- SQL dialect -->

        
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

 

        
<!-- Enable Hibernate's automatic session context management -->

        
<property name="current_session_context_class">thread</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 class="com.wsw.hibernate.model.Teacher" /> 

       

      
<!-- <mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>-->

 

    
</session-factory>

 

</hibernate-configuration>



 三:建立实体类:Teacher,由于我采用注解方式进行配置,所以需要再实体类上面加上注解。
       
 

package com.wsw.hibernate.model;

 

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

 

@Entity

@Table(name
="t_teacher")

public class Teacher implements Serializable {

 

    
private int id;

    

    
private String username;

    

    
private int age;

    

    @Id 

    @GenericGenerator(name 
= "generator", strategy = "increment")

    @GeneratedValue(generator 
= "generator")

    @Column(name 
= "id"

    
public int getId() {

       
return id;

    }


 

    
public void setId(int id) {

       
this.id = id;

    }


    

    @Column(name
="t_username")

    
public String getUsername() {

       
return username;

    }


    

    
public void setUsername(String username) {

       
this.username = username;

    }


    

    @Column(name
="t_age")

    
public int getAge() {

       
return age;

    }


    
public void setAge(int age) {

       
this.age = age;

    }


}



   

四:创建获取SessionFactory的单例类:


package com.wsw.hibernate.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    
private static final SessionFactory sessionFactory;

    
static {

        
try {

            
// Create the SessionFactory from hibernate.cfg.xml

            
//sessionFactory = new Configuration().configure().buildSessionFactory();

            sessionFactory 
= new AnnotationConfiguration().configure()

                    .buildSessionFactory();

        }
 catch (Throwable ex) {

            
// Make sure you log the exception, as it might be swallowed

            System.err.println(
"Initial SessionFactory creation failed." + ex);

            
throw new ExceptionInInitializerError(ex);

        }


    }


    
public static SessionFactory getSessionFactory() {

        
return sessionFactory;

    }


}

    
    五:实现hibernate的CURD操作:
    

package com.wsw.hibernate.action;

 

import java.util.List;

 

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.wsw.hibernate.model.Person;

import com.wsw.hibernate.model.Teacher;

import com.wsw.hibernate.util.HibernateUtil;

 

public class TeacherManager {

    
public static void main(String[] args) {

        
//selectTeacher_By_Load(1);

        insertTeacher();

        
//deleteTeacher();

        selectAll();


        
//updateTeacher();

        
//insertTeacher();

        
//createAndStoreTeacher();

        
//select_All_By_Get(2);

        
//select_AllPerson_By_Get();

        
//annotation();

        
//HibernateUtil.getSessionFactory().close();

    }


    
/**

     * 插入记录

     
*/


    
private static void insertTeacher() {

  

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();    

        Teacher teacher 
= new Teacher();

        teacher.setUsername(
"aaa");

        teacher.setAge(
25);

        session.save(teacher);

        session.getTransaction().commit();

        System.out.println(
"insert teacher successfully");

        

    }


    

    
/**

     * 删除记录操作

     
*/


    
private static void deleteTeacher() {

        
int count;

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Query query 
= session.createQuery("delete Teacher where id=?");     

        query.setParameter(
01);

        count 
= query.executeUpdate();                          // 删除记录采用Update方式

        session.getTransaction().commit();

        System.out.println(
"删除" + count + "条teacher记录");

    }


    

    
/**

     * 根据id采用load方式查询

     * 
@param id

     
*/


    
private static void selectTeacher_By_Load(int id) {

        Session session 
= HibernateUtil.getSessionFactory().openSession();

        
// load获取值不能采用这种方式获取session对象,因为load采用延迟加载/懒加载。而getCurrentSession()获取session时会自动关闭session对象,

        
// 所以会导致对象没有保存到内存中,然后你使用该对象了,导致该:org.hibernate.LazyInitializationException异常。

        
//Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 

        session.beginTransaction(); 

        Teacher teacher 
= (Teacher)session.load(Teacher.class, id);   // 只能是主键id获取对象值,不能以其他的表字段名获取对象值,否则,只能用HQL语句查询。

        System.out.println(
"load方式commit之前====>Id:" + teacher.getId() + " UserName:" + teacher.getUsername() + " Age:" + teacher.getAge());

        session.getTransaction().commit();

        System.out.println(
"load方式commit之后====》Id:" + teacher.getId() + " UserName:" + teacher.getUsername() + " Age:" + teacher.getAge());

        session.close(); 
// load获取值session方式需要手动关闭session对象,而通过getCurrentSession()则会自动关闭session对象

    }


    

    
/**

     * 根据id采用get方式查询

     * 
@param id

     
*/


    
private static void selectTeacher_By_Get(int id) {

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction(); 

        Teacher teacher 
= (Teacher)session.get(Teacher.class, id);

        System.out.println(
"get方式commit之前====>Id:" + teacher.getId() + " UserName:" + teacher.getUsername() + " Age:" + teacher.getAge());

        session.getTransaction().commit();

        System.out.println(
"get方式commit之后====>Id:" + teacher.getId() + " UserName:" + teacher.getUsername() + " Age:" + teacher.getAge());

    }


    

    
/**

     * 按条件查询记录

     
*/


    
private static void selectAll_By_Request() {

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Query query 
= session.createQuery("from Teacher where id=? and age=:tage"); //在条件语句中,可以用?和:两种方式。两者方式各有不同。

        query.setParameter(
02);                // 从0开始,而不是从1开始。采用?方式。

        
//query.setInteger(0, 2);                // 上面的query.setParameter(0, 2)也可以用query.setInteger(0, 2)代替,效果一样 

        query.setParameter(
"tage"27);          // 采用:方式。前面参数名与之前的:后面的参数名必须一致。

        
//query.setInteger("tage", 27);          // 上面的query.setParameter("tage", 27)也可以用query.setInteger("tage", 27)代替,效果一样 

        List
<Teacher> listteacher = (List<Teacher>)query.list();

        printList(listteacher);

    }


    

    
/**

     * 查询全部记录

     
*/


    
private static void selectAll() {

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Query query 
= session.createQuery("from Teacher");       

        List
<Teacher> listteacher = (List<Teacher>)query.list();

        printList(listteacher);

    }


    

    
/**

     * 更新操作

     
*/


    
private static void updateTeacher() {

        
int count;

        Session session 
= HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Query query
= session.createQuery("update Teacher set t_username='何小景' where id=?");

        query.setInteger(
02);

        count 
= query.executeUpdate();

        session.getTransaction().commit();

        System.out.println(
"更新" + count +"条记录");

    }


    
/**

     * 打印List<Person>对象集合

     * 
@param listteacher

     
*/


    
private static void printList(List<Teacher> listteacher){

        
for(Teacher teacher : listteacher) {

            System.out.println(
"Id:" + teacher.getId() + " UserName:" + teacher.getUsername() + " Age:" + teacher.getAge());

        }


    }


}


     

posted on 2012-06-30 10:29 奋斗成就男人 阅读(2943) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: