基于Hibernate实现CRUD

一个简单的练习项目:基于Hibernate实现CRUD

共有两个表,Teacher表、College表。单向的多对一映射关系。以下是我的代码实现。

1.项目的目录结构:

基于Hibernate实现CRUD

2.HibernateUtil.java:

//SessionFaction单态模式
public class HibernateUtil {
	private static SessionFactory sf=null;
	private static Configuration cfg=null;
	static {//在类加载的时候只能加载一次
		try {
			cfg = new Configuration().configure();
			sf=cfg.buildSessionFactory();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static SessionFactory getSessionFactory() {
		return sf;
	}
	public static void closeSessionFactory(){
		sf.close();
	}
}

3.Hibernate.cfg.xml:

<hibernate-configuration>
	<session-factory >
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
		<property name="hibernate.connection.driver_class ">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateTest?useSSL=false</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"> </property>
		<property name="show_sql">true</property>
		<!-- 保证每个读写线程有唯一的session实例 -->
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping resource="cn/hrbust/pojo/Teacher.hbm.xml"/>
		<mapping resource="cn/hrbust/pojo/College.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

4.Teacher.hbm.xml

<hibernate-mapping>
    <class name="cn.hrbust.pojo.Teacher" table="T_Teacher" select-before-update="true" dynamic-update="true">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <property name="gender"/>
        <property name="age"/> 
        <property name="course"/>
        <property name="phone"/>
       	<many-to-one name="college" column="collegeid" class="cn.hrbust.pojo.College" cascade="save"  not-null="true" />
    </class>
   
		
</hibernate-mapping>

5.College.hbm.xml

<hibernate-mapping>
    <class name="cn.hrbust.pojo.College" table="T_College" select-before-update="true" dynamic-update="true">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name" />
   
    </class>
</hibernate-mapping>

6.Dao层接口

public interface TeacherDao {
	void addTeacher(Teacher t);
	void deleteTeacher(int id);
	void updateTeacher(Teacher t,College c);
	List<Teacher> queryTeacher();
}

7.Dao层的实现类

public class TeacherDaoImpl implements TeacherDao {
	private SessionFactory sf = HibernateUtil.getSessionFactory();
	private Session session = sf.getCurrentSession();
	private Transaction ts = session.beginTransaction();
	private Query query = null;

	@Override
	public void addTeacher(Teacher t) {
		// TODO Auto-generated method stub
		session.save(t);
		ts.commit();

	}

	@Override
	public void deleteTeacher(int id) {
		// TODO Auto-generated method stub
		Teacher teacher = session.get(Teacher.class, id);//先获得对象
		session.delete(teacher);//再删除对象
		ts.commit();

	}

	@Override
	public void updateTeacher(Teacher t,College c) {
		// TODO Auto-generated method stub
		Teacher teacher =new Teacher();
		teacher.setId(t.getId());
		teacher.setName(t.getName());
		teacher.setName(t.getName());
		teacher.setGender(t.getGender());
		teacher.setAge(t.getAge());
		teacher.setCourse(t.getCourse());
		teacher.setPhone(t.getPhone());
		teacher.setCollege(t.getCollege());
		session.update(teacher);
		ts.commit();

	}

	@Override
	public List<Teacher> queryTeacher() {
		// TODO Auto-generated method stub
		query = session.createQuery(" from Teacher");
		List<Teacher> list = query.list();
		return list;

	}

}

8.测试类:

public class manageTeacher extends TestCase{
	public void testAdd() {
		TeacherDao teacherdao = null;
		Teacher teacher = null;
		try {
			
			teacherdao = new TeacherDaoImpl();
			
			College c=new College();
			c.setName("哈尔滨理工大学");

			Teacher t=new Teacher();
			t.setName("小美");
			t.setGender("女");
			t.setAge(33);
			t.setCourse("工科");
			t.setPhone(1234566666);
			t.setCollege(c);
			teacherdao.addTeacher(t);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
	}
	
	public void testDelete(){
		TeacherDao teacherdao = null;
		Teacher teacher = null;
		try {
			
			teacherdao = new TeacherDaoImpl();
			teacherdao.deleteTeacher(14);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
	}

	public void testUpdate() {
		TeacherDao teacherdao = null;
		Teacher teacher = null;
		try {
			
			teacherdao = new TeacherDaoImpl();
			College c=new College();
			c.setName("哈尔滨理工大学");

			Teacher t=new Teacher();
			t.setId(13);
			t.setName("小美老师");
			t.setGender("女");
			t.setAge(28);
			t.setCourse("工科");
			t.setPhone(88888888);
			t.setCollege(c);
	
			teacherdao.updateTeacher(t,c);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
	}
	
	public void testQuery() {
		TeacherDao teacherdao = null;
		Teacher teacher = null;
		try {
			
			teacherdao = new TeacherDaoImpl();
	
			List<Teacher> teachers = teacherdao.queryTeacher();
			for (int i=0;i<teachers.size();i++) { 
				Teacher t=(Teacher)teachers.get(i);
				System.out.println(t.getName()+" —— "+t.getGender()+" —— "+t.getAge()+" —— "+t.getCourse()+" —— "+t.getPhone()+" —— "+"所属学校:"+t.getCollege().getName());
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}	
	}
}

实验结果:

增加操作:

基于Hibernate实现CRUD

基于Hibernate实现CRUD

删除操作

删除前:

基于Hibernate实现CRUD

删除后:

基于Hibernate实现CRUD

修改操作

修改前:

基于Hibernate实现CRUD

修改后:

基于Hibernate实现CRUD

查询操作

基于Hibernate实现CRUD

 

上一篇:Datagridview全选,更新数据源代码


下一篇:一个小巧且容易上手的SSM增删改查(CRUD)项目——搞起来~