Hibernate实现数据库增、删、改、查

时间:2022-12-11 20:41:37

1.导入hibernate jar包和mysql jar包,修改配置文件hibernate.cfg.xml

 

<?xml version="1.0" encoding="gbk"?>
<!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 name="foo">
		<!-- 配置数据库信息 --> 
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="connection.url">jdbc:mysql:///hibernate1</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.username">root</property>
		<property name="hibernate.connection.password">123</property>

		<!-- 其他配置 -->
		<property name="hibernate.show_sql">true</property>
		
		<!-- 导入映射文件 
		
		-->
		<mapping resource="demo/User.hbm.xml"/>
	
	
	
	</session-factory>
</hibernate-configuration>
2.创建数据库中的表,根据表创建实体对象

package demo;

public class User {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "id="+id+" name="+name;
	}
}

3.根据表和对象,配置映射关系 User.hbm.xml

<?xml version="1.0" encoding="gbk"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- 

  This mapping demonstrates 

     (1) a table-per-subclass mapping strategy
         
     (2) a simple component mapping
     
     (3) recursive associations withing an inheritance tree
     
-->

<hibernate-mapping 
	package="demo">
	
	<class name="User" table="t_user">
		
		<id name="id" type="int" column="id" >
			<generator class="native"/> <!--表示自动增长-->
		</id>

        <property name="name" type="string" column="name" />
		
	</class>
	

</hibernate-mapping>

4.写个HIbernate小工具,方便快速得到SessionFactory,得到session

package demo;


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

public class HibernateUtils {
	private static SessionFactory sessionFactory;
	
	//初始化SessionFactory
	static{
//		Configuration cfg=new Configuration();
//		cfg.configure();//读取默认的配置文件hibernate.cfg.xml
//		cfg.configure("hibernate.cfg.xml");
//		sessionFactory=cfg.buildSessionFactory();
		sessionFactory=new Configuration()
						.configure()
						.buildSessionFactory();
	}
	/**
	 * 获取全局唯一的SessionFactory
	 * @return
	 */
	public static SessionFactory getSessionFactory() {
		
		return sessionFactory;
	}
	/**
	 * 从全局唯一的SessionFactory打开session
	 * @return
	 */
	public static Session openSession() {
		return sessionFactory.openSession();
		
	}
}

5.在UserDao中完成具体功能

package demo;

import java.util.List;

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

public class UserDao {
	/**
	 * 增
	 * @param user
	 */
	public void add(User user){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
	}
	/**
	 * 删
	 * @param user
	 */
	public void delete(int id){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			session.delete(session.get(User.class, id));
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
	}
	/**
	 * 改
	 * @param user
	 */
	public void update(User user){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			session.update(user);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
	}
	/**
	 * 查
	 * @param id
	 */
	public User getById(int id){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			User user=(User) session.get(User.class, id);
			tx.commit();
			return user;
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
	}
	
	public List<User> findAll(){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			List<User> list=session.createQuery( //使用HQL查询
					"FROM User")
					.list();//根据条件得到list
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
		
	}
	
	/**
	 * 分页,返回一页的数据列表
	 * @param firstResult 从结果列表中的那个索引开始取数据
	 * @param maxResults 最多取多少条数据
	 * @return  list+count返回的条数
	 */
	public QueryResult findAll(int firstResult, int maxResults){
		Session session=HibernateUtils.openSession();
		Transaction tx=null;
		try{
			tx=session.beginTransaction();
			//查询一页的数据列表
			//方式一
//			Query query=session.createQuery("FROM User");
//			query.setFirstResult(firstResult);
//			query.setMaxResults(maxResults);
//			List<User> list=query.list();
			//方式二
			List<User> list=session.createQuery("FROM User")
					.setFirstResult(firstResult)
					.setMaxResults(maxResults)
					.list();
			//查询总记录数
			Long count=(Long)session.createQuery("SELECT COUNT(*) FROM User")
					.uniqueResult();
			tx.commit();
			return new QueryResult(count.intValue(),list);
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
			} finally{
				session.close();
			}
	}
}

6.右击包名-new-Junit Test Case,也可以一一测试,对UserDao进行测试 

package demo;

import static org.junit.Assert.*;

import java.util.List;

import org.hibernate.SessionFactory;
import org.junit.Test;

public class UserDaoTest {
	private UserDao userDao=new UserDao();
	@Test
	public void testAdd() {
		User user=new User();
		user.setName("Lily");
		userDao.add(user);
		
	}
	
	@Test
	public void testAdd_25() {
		for(int i=1;i<=25;i++){
			User user=new User();
			user.setName("test_"+i);
			userDao.add(user);
		}
		
	}

	@Test
	public void testDelete() {
		userDao.delete(1);
	}

	@Test
	public void testUpdate() {
		//从数据库中获取一条已存在的数据
		User user=userDao.getById(1);
		user.setName("haha");
		userDao.update(user);
	}

	@Test
	public void testGetById() {
		User user =userDao.getById(1);
		System.out.println(user);
	}

	@Test
	public void testFindAll() {
		List<User> users=userDao.findAll();
		for(User user:users){
			System.out.println(user);
		}
	}

	@Test
	public void testFindAllIntInt() {
//		QueryResult qr=userDao.findAll(0,10); //第1页,每页10条
//		QueryResult qr=userDao.findAll(10,10);
		QueryResult qr=userDao.findAll(20,10);
		
		//显示结果
		System.out.println("总记录数:"+qr.getCount());
		for(Object user:qr.getList()){
			System.out.println(user);
		}
	}

}