Hibernate做增删改查(C,R,U,D)

最近学习了Hibernate框架,做了一个简单的单表增删改查,供初学者学习参考

首先要配置Hibernate的配置文件:

hibernate.cfg.xml:

<!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>
		<!--
           连接数据库的一些配置
        -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///laok</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>


		<!-- 配置数据库方言
            由于hibernate支持多种数据库,那么每一个数据库在sql方法都有一些不同
            所以根据不同的数据库配置方言
         -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!--

           #hibernate.hbm2ddl.auto create-drop:启动hibernate,就会生成新表,程序结束,自动删除  测试用
           #hibernate.hbm2ddl.auto create  如果没有自动生成  测试用
           #hibernate.hbm2ddl.auto update  有,就用,没有,就生成(改变你的表结构) 生产用
           #hibernate.hbm2ddl.auto validate 启动时,校验,如果有问题,报错。没有问题的话,就没有问题
         -->
		<!-- hbm2ddl -->
		<property name="hibernate.hbm2ddl.auto">update</property>

		<!-- 以上的6项必须有 -->

		<!-- 可选的配置 -->
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.show_sql">true</property>

		


		<!-- 加载哪些映射文件 -->
		<mapping resource="com/baidu/hibernate/Student.hbm.xml"/>

	</session-factory>
</hibernate-configuration>

创建持久化类:

Student.java:

public class Student {
	
	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Student(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	

}

创建映射文件:

Student.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!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="com.baidu.hibernate.Student" table="t_student">
		<id name="id" column="id">
			<generator class="native"></generator><!-- 設置主鍵 -->
		</id>
		<property name="name" column="name" type="string"></property><!-- 設置字段屬性 -->
		<property name="age" column="age" type="int"></property><!-- 設置字段屬性 -->
	</class>
</hibernate-mapping>

然后是Dao:

StudnetDaoImpl.java:

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.baidu.hibernate.Student;
import com.baidu.utils.HibernateUtils;

public class StudentDaoImpl {
	
	//列表展示
	public List<Student> showlist() {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        List<Student> list=null;
        try {
        	Query query = session.createQuery("from Student");
        	 list =(List<Student>) query.list();
        	 tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(null !=tx) {
				tx.rollback();
			}
		}finally {
			HibernateUtils.close(session);
		}
        
        return list;
    }
	
	//添加操作
    public void addlist(Student student) {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        try {
        	session.save(student);
            tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(null !=tx) {
				tx.rollback();
			}
		}finally {
			HibernateUtils.close(session);
		}
        
    }

    //刪除操作
    public void deletelist(Integer id) {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        try {
        	 Student student =(Student) session.get(Student.class, id);
             session.delete(student);
             tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(null !=tx) {
				tx.rollback();
			}
		}finally {
			 HibernateUtils.close(session);
		}
       
    }
    
    //更新前
    public Student toupdate(Integer id) {
    	Student student=null;
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        try {
        	student =(Student) session.get(Student.class, id);
            tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(null !=tx) {
				tx.rollback();
			}
		}finally {
			HibernateUtils.close(session);
		}
        
        return student;
    }
    //更新操作
    public void updatelist(Student student) {
        Session session = HibernateUtils.openSession();
        Transaction tx = session.beginTransaction();
        try {
        	session.update(student);
            tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(null !=tx) {
				tx.rollback();
			}
		}finally {
			HibernateUtils.close(session);
		}
        
    }
}

工具类:

HibernateUtils.java:

扫描二维码关注公众号,回复: 3809916 查看本文章
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

	private static SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Session openSession() {

		Session session = sessionFactory.openSession();
		return session;
	}

	public static void close(Session session) {
		if (null != session) {
			session.close();
		}
	}

}

actiion和jsp中的代码我就不贴了,想看的可以翻阅我之前写的博客。

猜你喜欢

转载自blog.csdn.net/weixin_42719412/article/details/83090874
今日推荐