Hibernate操作示例

    技术2026-08-15  23

    一个JavaWeb 项目

    1.创建数据库脚本db.sql

    drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table CUSTOMERS ( ID int not null primary key, NAME varchar(15) not null, EMAIL varchar(128) not null, PASSWORD varchar(8) not null, PHONE int , ADDRESS varchar(255), SEX char(1) , IS_MARRIED bit, DESCRIPTION text, IMAGE blob, BIRTHDAY date, REGISTERED_TIME timestamp );

    2.搭建Hibernate的开发环境(我用的是Hibernate3.2)

    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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- URL --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SAMPLEDB</property> <!-- 用户名 --> <property name="hibernate.connection.username">root</property> <!-- 密码 --> <property name="hibernate.connection.password">root</property> <!-- 数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 打印SQL语句 --> <property name="hibernate.show_sql">true</property> <!-- 映射文件的位置 --> <mapping resource="cdl/Customer.hbm.xml" /> </session-factory> </hibernate-configuration>

    3.创建持久化类文件Customer.java

    package cdl; import java.sql.Timestamp; import java.util.Date; /** * 定义持久化类(要符合JavaBean规范) * @author Root * */ public class Customer implements java.io.Serializable { //属性 private Integer id; private String name; private String email; private String password; private int phone; private String address; private char sex; private boolean married; private String description; private byte[] image; // 处理图片用的 private Date birthday; private Timestamp registeredTime; //空构造 public Customer() { } //getter and setter 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } //isMarried==getMarried public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getRegisteredTime() { return registeredTime; } public void setRegisteredTime(Timestamp registeredTime) { this.registeredTime = registeredTime; } }

     

    4.创建映射文件Customer.hbm.xml

    <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="cdl.Customer" table="CUSTOMERS"> <id name="id" column="ID" type="int"> <generator class="increment"/> <!-- id由Hibernate负责生成 --> </id> <property name="name" column="NAME" type="string" not-null="true"/> <property name="email" column="EMAIL" type="string" not-null="true"/> <property name="password" column="PASSWORD" type="string" not-null="true"/> <property name="phone" column="PHONE" type="int"/> <property name="address" column="ADDRESS" type="string"/> <property name="sex" column="SEX" type="character"/> <property name="married" column="IS_MARRIED" type="boolean"/> <property name="description" column="DESCRIPTION" type="text"/> <property name="image" column="IMAGE" type="binary"/> <!-- 对应属性的 byte[]类型,处理图片用的 --> <property name="birthday" column="BIRTHDAY" type="date"/> <property name="registeredTime" column="REGISTERED_TIME" type="timestamp"/> </class> </hibernate-mapping>

    5.编写Service文件 CustomerService(这里包含了方法测试)

    package cdl; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletContext; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class CustomerService { /** * 初始化Hibernate,创建SessionFactory实例 */ private static SessionFactory sf; static{ Configuration cfg=new Configuration().configure(); sf=cfg.buildSessionFactory(); } /** * 查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息 */ public void findAllCustomers(ServletContext context,PrintWriter out) throws Exception{ Session session=sf.openSession(); Query query=session.createQuery("from Customer as c order by c.name "); List list=query.list(); Iterator it=list.iterator(); while(it.hasNext()){ this.printCustomer(context,out,(Customer) it.next()); } session.close(); } /** * 持久化Customer对象 */ public void saveCustomer(Customer customer){ Session session=sf.openSession(); Transaction tx=null; try{ tx=session.beginTransaction(); session.save(customer); //持久化customer对象 tx.commit(); }catch(HibernateException e){ if(tx!=null){ tx.rollback(); } throw e; }finally{ if(session!=null){ session.close(); } } } /** * 更新Customer对象 */ public void updateCustomer(Customer customer){ Session session=sf.openSession(); Transaction tx=null; try{ tx=session.beginTransaction(); session.update(customer); //更新customer对象 //session.saveOrUpdate(customer); 根据customer对象的状态,选择是持久化customer对象还是更新customer对象 tx.commit(); }catch(HibernateException e){ if(tx!=null){ tx.rollback(); } throw e; }finally{ if(session!=null){ session.close(); } } } /** * 删除Customer对象 */ public void deleteCustomer(int id){ Session session=sf.openSession(); Transaction tx=null; try{ tx=session.beginTransaction(); Customer c=(Customer)session.get(Customer.class, id); //根据I的加载一个Customers对象 session.delete(c); //删除加载的对象 tx.commit(); }catch(HibernateException e){ if(tx!=null){ tx.rollback(); } throw e; }finally{ if(session!=null){ session.close(); } } } /** * 删除Customer对象 */ public void deleteCustomer2(int id){ Session session=sf.openSession(); Transaction tx=null; try{ tx=session.beginTransaction(); String hql="delete from Customer as c where c.id=?"; Query query=session.createQuery(hql); query.setParameter(0, id); //设置参数 query.executeUpdate(); //执行删除操作 tx.commit(); }catch(HibernateException e){ if(tx!=null){ tx.rollback(); } throw e; }finally{ if(session!=null){ session.close(); } } } /** * 选择向控制台还是Web网页输出Customer对象的信息 */ private void printCustomer(ServletContext context,PrintWriter out,Customer customer)throws Exception{ if(context!=null){ printCustomerInWeb(context,out,customer); }else{ printCustomer( out,customer); } } /** * 把Customer对象的信息输出到控制台 */ private void printCustomer(PrintWriter out,Customer customer)throws Exception{ byte image[]=customer.getImage(); OutputStream outPut=new FileOutputStream("photo.gif"); outPut.write(image); outPut.close(); out.println("控制台输出"); out.println(customer.getName()+"的个人信息如下:"); out.println("id:"+customer.getId()); out.println("name:"+customer.getName()); out.println("email:"+customer.getEmail()); out.println("password:"+customer.getPassword()); out.println("phone"+customer.getPhone()); out.println("address:"+customer.getAddress()); String sex=customer.getSex()=='M'?"男":"女"; out.println("sex:"+sex); String marry=customer.isMarried()==true?"已婚":"未婚"; out.println("married:"+marry); out.println("description:"+customer.getDescription()); out.println("birthday:"+customer.getBirthday()); out.println("registeredTime:"+customer.getRegisteredTime()); out.close(); } /** * 把Customer对象的信息输出到动态网页 */ private void printCustomerInWeb(ServletContext context,PrintWriter out,Customer customer)throws Exception{ byte image[]=customer.getImage(); String path=context.getRealPath("/"); OutputStream outPut=new FileOutputStream(path+"photo.gif"); outPut.write(image); outPut.close(); out.println("<font color='red'>网页输出</font><br />"); out.println(customer.getName()+"的个人信息如下:<br />"); out.println("id:"+customer.getId()+"<br />"); out.println("name:"+customer.getName()+"<br />"); out.println("email:"+customer.getEmail()+"<br />"); out.println("password:"+customer.getPassword()+"<br />"); out.println("phone"+customer.getPhone()+"<br />"); out.println("address:"+customer.getAddress()+"<br />"); String sex=customer.getSex()=='M'?"男":"女"; out.println("sex:"+sex+"<br />"); String marry=customer.isMarried()==true?"已婚":"未婚"; out.println("married:"+marry+"<br />"); out.println("description:"+customer.getDescription()+"<br />"); out.println("birthday:"+customer.getBirthday()+"<br />"); out.println("registeredTime:"+customer.getRegisteredTime()+"<br />"); out.println("<img src="photo.gif" mce_src="photo.gif"/>"); out.close(); } //测试 public static void main(String[] args) throws Exception { /* 持久化对象 InputStream in=new FileInputStream("src/photo.gif"); byte []image =new byte[in.available()]; in.read(image); Customer c=new Customer(); c.setAddress("大连"); c.setBirthday(java.sql.Date.valueOf("1999-09-09")); c.setDescription("I like java"); c.setEmail("516673731@qq.com"); c.setImage(image); c.setMarried(false); c.setName("root"); c.setPassword("123"); c.setPhone(98765); //c.setRegisteredTime(new java.sql.Timestamp(0)); //不用设置,数据库提供值 c.setSex('M'); new CustomerService().saveCustomer(c); //执行了两条SQL 语句 //1.找到最大的id //select max(ID) from CUSTOMERS //2.添加记录 //insert into CUSTOMERS (NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX, IS_MARRIED, DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME, ID) //values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) */ /*更新对象 InputStream in=new FileInputStream("src/nopic.jpg"); byte []image =new byte[in.available()]; in.read(image); Customer c=new Customer(); c.setAddress("北京"); c.setBirthday(java.sql.Date.valueOf("2009-10-10")); c.setDescription("I like Hibernate"); c.setEmail("12345@qq.com"); c.setImage(image); c.setMarried(true); c.setName("小红"); c.setPassword("789"); c.setPhone(55667788); //c.setRegisteredTime(new java.sql.Timestamp(0)); //不用设置,数据库提供值 c.setSex('F'); c.setId(1); //必须设置,不然无法完成更新--> 持久化与更新就差在这 new CustomerService().updateCustomer(c); // 执行了一条SQL语句 //update CUSTOMERS //set NAME=?, EMAIL=?, PASSWORD=?, PHONE=?, ADDRESS=?, SEX=?, IS_MARRIED=?, DESCRIPTION=?, IMAGE=?, BIRTHDAY=?, REGISTERED_TIME=? //where ID=? */ //查询对象 //new CustomerService().findAllCustomers(null,new PrintWriter(System.out,true)); //控制台输出 //执行了一条SQL语句 //select customer0_.ID as ID0_, customer0_.NAME as NAME0_, customer0_.EMAIL as EMAIL0_, customer0_.PASSWORD as PASSWORD0_, customer0_.PHONE as PHONE0_, customer0_.ADDRESS as ADDRESS0_, customer0_.SEX as SEX0_, customer0_.IS_MARRIED as IS8_0_, customer0_.DESCRIPTION as DESCRIPT9_0_, customer0_.IMAGE as IMAGE0_, customer0_.BIRTHDAY as BIRTHDAY0_, customer0_.REGISTERED_TIME as REGISTERED12_0_ //from CUSTOMERS customer0_ //order by customer0_.NAME //删除对象 //int id=1; //new CustomerService().deleteCustomer(id); // 执行了2条SQL语句 //select customer0_.ID as ID0_0_, customer0_.NAME as NAME0_0_, customer0_.EMAIL as EMAIL0_0_, customer0_.PASSWORD as PASSWORD0_0_, customer0_.PHONE as PHONE0_0_, customer0_.ADDRESS as ADDRESS0_0_, customer0_.SEX as SEX0_0_, customer0_.IS_MARRIED as IS8_0_0_, customer0_.DESCRIPTION as DESCRIPT9_0_0_, customer0_.IMAGE as IMAGE0_0_, customer0_.BIRTHDAY as BIRTHDAY0_0_, customer0_.REGISTERED_TIME as REGISTERED12_0_0_ //from CUSTOMERS customer0_ //where customer0_.ID=? //delete from CUSTOMERS where ID=? //删除对象 //int id=2; //new CustomerService().deleteCustomer2(id); //执行了一条SQL语句 //delete from CUSTOMERS where ID=? //因为只发送了一条SQL语句到数据库,所以效率会比之前的删除方法提高一些 } }

    6.编写CustomerServlet ,它是一个Servlet文件,目的是把信息输出到网页上

    package cdl; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //查询对象-->输出到网页上 new CustomerService().findAllCustomers(this.getServletContext(),out); //执行了一条SQL语句 //select customer0_.ID as ID0_, customer0_.NAME as NAME0_, customer0_.EMAIL as EMAIL0_, customer0_.PASSWORD as PASSWORD0_, customer0_.PHONE as PHONE0_, customer0_.ADDRESS as ADDRESS0_, customer0_.SEX as SEX0_, customer0_.IS_MARRIED as IS8_0_, customer0_.DESCRIPTION as DESCRIPT9_0_, customer0_.IMAGE as IMAGE0_, customer0_.BIRTHDAY as BIRTHDAY0_, customer0_.REGISTERED_TIME as REGISTERED12_0_ //from CUSTOMERS customer0_ //order by customer0_.NAME } catch (Exception e) { e.printStackTrace(); } //out.close(); } }

    7.在web.xml中配置这个Servlet

    <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>CustomerServlet</servlet-name> <servlet-class>cdl.CustomerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CustomerServlet</servlet-name> <url-pattern>/CustomerServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

    附:

     

    控制台输出

    在网页上的显示

     

    最新回复(0)