hibernate操作数据库,初学例子一

log4j 配置文件

 

#FATAL > ERROR > WARN > INFO > DEBUG

# Output pattern : date [thread] priority category - message
log4j.rootLogger=info, Console, RollingFile

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#RollingFile
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=logs/webTest.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#Project defalult level
#log4j.logger.org.hibernate.cache=FATAL

 

 

 

hibernate.properties  hibernate属性文件

 

#hibernate settings
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/test
hibernate.connection.username=root
hibernate.connection.password=zwc0913
hibernate.show_sql=true

 

bean  customer 对应的属性文件

package bean;

import java.io.Serializable;
import java.sql.Timestamp;

/**
 *
 * @author zwc
 *
 */

@SuppressWarnings("serial")
public class Customer implements Serializable{
 private Long id;
 private String name;
 private int phone;
 private boolean married;
 private char sex;
 private byte[]image;
 private Timestamp registeredTime;
 
 public Customer(){
  //empty
 }
 
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getPhone() {
  return phone;
 }
 public void setPhone(int phone) {
  this.phone = phone;
 }
 public boolean isMarried() {
  return married;
 }
 public void setMarried(boolean married) {
  this.married = married;
 }
 public char getSex() {
  return sex;
 }
 public void setSex(char sex) {
  this.sex = sex;
 }
 public byte[] getImage() {
  return image;
 }
 public void setImage(byte[] image) {
  this.image = image;
 }
 public Timestamp getRegisteredTime() {
  return registeredTime;
 }
 public void setRegisteredTime(Timestamp registeredTime) {
  this.registeredTime = registeredTime;
 }
}

 

custome对应的hibernate配置文件  Customer.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>
 <class name="bean.Customer" table="t_customer">
  <id name="id" column="id" type="long">
   <generator class="native"/>
  </id>
  <property name="name" column="name" type="string" not-null="false"/>
  <property name="phone" column="phone" type="integer"/>
  <property name="married" column="married" type="boolean"/>
  <property name="sex" column="sex" type="character"/>
  <property name="image" column="image" type="binary"/>
  <property name="registeredTime" column="registered_time" type="timestamp"/>
 </class>
</hibernate-mapping>

 

 

测试的servelet  类

 

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import bean.Customer;

 

/**
 *
 * @author zwc
 *
 */

@SuppressWarnings("serial")
public class OperateCustomer extends HttpServlet {
 private static Logger logger = Logger.getLogger(OperateCustomer.class);
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request,response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  
  Session session = new Configuration()
   .addClass(Customer.class)
   .buildSessionFactory()
   .openSession();
  
  Transaction t = (Transaction) session.beginTransaction();

  Customer c = new Customer();
  c.setName("Customer1");
  c.setMarried(false);
  c.setSex('F');
  c.setPhone(123456);
  c.setRegisteredTime(new Timestamp(System.currentTimeMillis()));  
  
  try {
   session.beginTransaction();
   session.save(c);
   t.commit();
  } catch (Exception e) {
   logger.warn("保存Customer失败");
   try {
    t.rollback();
   } catch (Exception e1) {
    logger.warn("回滚失败");
   }
  }
  Query query = session.createQuery("from Customer");
  
  Iterator<Customer> i = (Iterator<Customer>) query.iterate();
  while(i.hasNext()){
   c = i.next();
   out.write(c.getName());
  }
  
 }

}

 

 

你可能感兴趣的:(hibernate操作数据库,初学例子一)