Hibernate系列(五):利用Hibernate完成简单的CRUD操作

这里利用Hibernate操作数据库完成简单的CRUD操作。

首先,我们需要先写一个javabean:

package cn.itcast.domain;

import java.util.Date;

public class User {
	private int id;
	private String name;
	private Date birthday;
	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;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	
}
然后呢,写上它的映射文件:User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping 
	package="cn.itcast.domain">

	<class name="User">
		<id name="id">
			<generator class="native"/> 
		</id>
		<property name="name" unique="true" />
		<property name="birthday" />
	</class>
	
</hibernate-mapping>


继续我们需要写出数据库的映射文件: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">

<hibernate-configuration>
	<session-factory>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/test
		</property>
		<property name="connection.username">sa</property>
		<property name="connection.password">123456</property>
		
		<property name="hbm2ddl.auto">update</property>
		<property name="show_sql">true</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<mapping resource="cn/itcast/domain/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>


当这些都完成之后,我们需要的就是编写Dao层了。

首先,我们得实现Dao层的接口(interface):UserDao.java

package cn.itcast.dao;

import cn.itcast.domain.User;

public interface UserDao {
	public void saveUser(User user);
	
	public User findUserByName(String name);
	
	public User findUserById(int id);
	
	public void updateUser(User user);
	
	public void remove(User user);
}


并且我们需要写一个简单的HinbernateUtil类来获得session:HibernateUtil.java

package cn.itcast.dao;

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

public final class HibernateUtil {
	private static SessionFactory sessionFactory;
	
	private HibernateUtil(){
		
	}
	static{
		Configuration cfg = new Configuration();
		cfg.configure();
		sessionFactory = cfg.buildSessionFactory();
	}
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	public static Session getSession(){
		return sessionFactory.openSession();
	}
}
接下来,我们就要写Dao层的实现了:UserDaoImpl.java

package cn.itcast.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import cn.itcast.dao.HibernateUtil;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;

public class UserDaoImpl implements UserDao {
	@Override
	public void saveUser(User user) { //保存一个对象
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(user);
			tx.commit();
		}finally{
			if(s!=null){
				s.close();
			}
		}

	}

	@Override
	public User findUserByName(String name) { //通过name查找一个对象
		Session s = null;
		try{
			s = HibernateUtil.getSession();
			Criteria c = s.createCriteria(User.class);
			c.add(Restrictions.eq("name", name));
			User user = (User)c.uniqueResult();//这里返回的是唯一的
			return user;
		}finally{
			if(s!=null){
				s.close();
			}
		}
	}

	@Override
	public User findUserById(int id) { //通过id查找一个对象
		Session s = null;
		try{
			s = HibernateUtil.getSession();
			User user = (User) s.get(User.class, id);
			return user;
		}finally{
			if(s!=null){
				s.close();
			}
		}
	}

	@Override
	public void updateUser(User user) { //更新一个对象
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.update(user);
			tx.commit();
		}finally{
			if(s!=null){
				s.close();
			}
		}

	}

	@Override
	public void remove(User user) { //删除一个对象
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(user);
			tx.commit();
		}finally{
			if(s!=null){
				s.close();
			}
		}
	}

}


最后,我们编写一个测试类类验证是否成功:DaoTest.java

package cn.test;

import java.util.Date;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoHibernateImpl;
import cn.itcast.domain.User;

public class DaoTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UserDao dao = new UserDaoHibernateImpl();
		User user = new User();
		user.setName("name");
		user.setBirthday(new Date());
		dao.saveUser(user);
		
		user.setName("new name");
		dao.updateUser(user);
		
		User u = dao.findUserByName(user.getName());
		
		dao.remove(u);

	}

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。