Hibernate的CRUD操作实例

实体类User.java

package org.myclover.user;

import java.util.Date;

public class User {
private int userId;
private String userName;
private String userSex;
private String userEmail;
private Date userBirthday;

public int getUserId() {
  return userId;
}

public void setUserId(int userId) {
  this.userId = userId;
}

public String getUserName() {
  return userName;
}

public void setUserName(String userName) {
  this.userName = userName;
}

public String getUserSex() {
  return userSex;
}

public void setUserSex(String userSex) {
  this.userSex = userSex;
}

public String getUserEmail() {
  return userEmail;
}

public void setUserEmail(String userEmail) {
  this.userEmail = userEmail;
}

public Date getUserBirthday() {
  return userBirthday;
}

public void setUserBirthday(Date userBirthday) {
  this.userBirthday = userBirthday;
}
}


类映射文件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="org.myclover.user">
<class name="User" table="t_user">
  <id name="userId" column="user_id">
   <generator class="native"></generator>
  </id>
  <!-- type属性中的类型首字母是小写的 -->
   <property name="userName" type="string" not-null="true" />
   <property name="userSex" type="string" />
   <property name="userEmail" type="string" />
   <property name="userBirthday" type="date" />
</class>
</hibernate-mapping>



CRUD的代码

package org.myclover.user.test;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.myclover.user.User;
import org.myclover.util.HibernateUtils;

public class TestUser extends TestCase {
public void testSaveUser() {
  Session session = null;
  Transaction tran = null;
  User user = null;
  try {
   session = HibernateUtils.getSession();//创建session
   tran = session.beginTransaction();//开启事务
   user = new User();
   //Transient状态
   user.setUserName("孙燕姿");
   user.setUserSex("女");
   user.setUserEmail("[email protected]");
   user.setUserBirthday(new Date());
   session.save(user);
   //persistent状态,当属性发生改变的时候,hibernate会自动和数据库同步,最后的结果
   //是下面的结果
   //user.setUserName("燕 姿");//相当于update
   //session.update(user);//这个语句有没有效果都一样
   tran.commit();// 提交事务
  } catch (Exception e) {
   e.printStackTrace();
   tran.rollback();//回滚事务
  } finally {
   HibernateUtils.closeSession(session);//关闭session
  }
  //detached状态,hibernate和数据库不同步,数据不能被更改
  user.setUserName("李四");
}

public void testGetUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
   //马上发出查询sql,加载User对象
   User user = (User) session.get(User.class, 3);//采用get加载数据,如果数据库中不存在相应的数据,返回null
   System.out.println("userId= " + user.getUserId());
   System.out.println("userName= " + user.getUserName());
   System.out.println("userSex= " + user.getUserSex());
   System.out.println("userEmail= " + user.getUserEmail());
   System.out.println("userBirthday= " + user.getUserBirthday());
   //persistent状态,当属性发生改变的时候,hibernate会自动和数据库同步
   //数据已经被更新,最终数据库里面的值是下面更改过的值
   //user.setUserName("蔡依林");
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

public void testLoadUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
   //不会发出查询sql,因为load方法实现了lazy(懒加载或延迟加载)
   //延迟加载:只有真正使用这个对象的时候,才加载(发出sql语句)
   //hibernate延迟加载实现原理是代理方式
   User user = (User) session.load(User.class, 14);//采用load加载数据,如果数据库中没有相应的数据,那么抛出ObjectNotFoundException
   System.out.println("userId= " + user.getUserId());
   System.out.println("userName= " + user.getUserName());
   System.out.println("userSex= " + user.getUserSex());
   System.out.println("userEmail= " + user.getUserEmail());
   System.out.println("userBirthday= " + user.getUserBirthday());
   //persistent状态,当属性发生改变的时候,hibernate会自动和数据库同步
   //数据已经被更新,最终数据库里面的值是下面更改过的值
   //user.setUserName("陈慧琳");
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

public void testQueryAllUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
   Query query = session.createQuery("from User");
   query.setFirstResult(0);//每页的第一条记录
   query.setMaxResults(4);// 每页显示的记录数目
   List userList = query.list();
   for (Iterator iterator = userList.iterator(); iterator.hasNext();) {
    User user = (User) iterator.next();
    System.out.println("userId= " + user.getUserId());
    System.out.println("userName= " + user.getUserName());
    System.out.println("userSex= " + user.getUserSex());
    System.out.println("userEmail= " + user.getUserEmail());
    System.out.println("userBirthday= " + user.getUserBirthday());
    System.out.println("=======================================");
   }
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

public void testUpdateUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
   //手动构造的detached状态的对象
   User user = new User();
   user.setUserId(15);
   user.setUserName("方方");
   user.setUserEmail("[email protected]");
   session.update(user);
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

public void testDeleteUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
  /* //手动构造的detached状态的对象
   User user = new User();
   user.setUserName("王五");
   session.delete(user);*/
      User user = (User) session.load(User.class, 15);
   session.delete(user);
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

public void testDelUser() {
  Session session = null;
  try {
   session = HibernateUtils.getSession();
   session.beginTransaction();
   /*//手动构造的detached状态的对象
   User user = new User();
   user.setUserName("王五");
   session.delete(user);*/
   User user = (User) session.get(User.class, 14);
   session.delete(user);
   session.getTransaction().commit();
  } catch (Exception e) {
   e.printStackTrace();
   session.getTransaction().rollback();
  } finally {
   HibernateUtils.closeSession(session);
  }
}

}

你可能感兴趣的:(sql,Hibernate,xml,qq,JUnit)