简单易懂的hibernate例子

数据库文件:myproject.sql

/*
MySQL Data Transfer
Source Host: localhost
Source Database: myproject
Target Host: localhost
Target Database: myproject
Date: 2009/8/26 17:23:12
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `users` VALUES ('34', '测试4', '123456', '[email protected]');
INSERT INTO `users` VALUES ('35', '测试5', '123456', '[email protected]');
INSERT INTO `users` VALUES ('36', '测试6', '123456', '[email protected]');
INSERT INTO `users` VALUES ('37', '测试7', '123456', '[email protected]');
INSERT INTO `users` VALUES ('38', '测试8', '123456', '[email protected]');


 

实体类:User.java
package usermap;
public class User {
 private int id;
 private String name;
 private String password;
 private String email;
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
}
 
hibernate类:HibernateBase.java
package usermap;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
public abstract class HibernateBase {
 protected SessionFactory sessionFactory;// 会话工厂,用于创建会话
 protected Session session;// hibernate会话
 protected Transaction transaction; // hiberante事务
 public HibernateBase() throws HibernateException {
  this.initHibernate();
 }
 // 帮助方法
 protected void initHibernate() throws HibernateException {
  // 装载配置,构造SessionFactory对象
  sessionFactory = new Configuration().configure().buildSessionFactory();
 }
 /**
  *开始一个hibernate事务
  */
 protected void beginTransaction() throws HibernateException {
  session = sessionFactory.openSession();
  transaction = session.beginTransaction();
 }
 /**
  *结束一个hibernate事务。
  */
 protected void endTransaction(boolean commit) throws HibernateException {
  if (commit) {
   transaction.commit();
  } else {
   // 如果是只读的操作,不需要commit这个事务。
   transaction.rollback();
  }
  session.close();}
}
 bean类:UserBean.java
 
package usermap;   
   
import org.hibernate.*;   
import org.hibernate.cfg.*;   
import java.util.*;   
   
/**  
 * 和course相关的业务逻辑  
 */   
public class UserBean extends HibernateBase {   
    public UserBean() throws HibernateException {   
        super();   
    }   
   
    /**  
     * 增加一个Course  
     */   
    public void addUser(User user) throws HibernateException {   
        beginTransaction();   
        session.save(user);   
        endTransaction(true);   
    }   
   
    /**  
     * 查询系统中所有的Course,返回的是包含有Course持久对象的Iterator。  
     */   
    public Iterator getAllUsers() throws HibernateException {   
        String queryString = "from User u order by u desc";   
        beginTransaction();   
        Query query = session.createQuery(queryString);   
        Iterator it = query.iterate();   
        return it;   
    }   
   
    /**  
     * 删除给定ID的course  
     */   
    public void deleteUser(String id) throws HibernateException {   
        beginTransaction();   
        User user = (User) session.load(User.class, id);   
        session.delete(user);   
        endTransaction(true);   
    }   
   
    /**  
     * 按course的名字进行模糊查找,返回的是包含有Course持久对象的Iterator。  
     */   
    public Iterator getSomeUser(String name) throws HibernateException {   
        String queryString = "select u from User as u where u.name like :name";   
        beginTransaction();   
        Query query = session.createQuery(queryString);   
        query.setString("name", "%" + name + "%");   
        Iterator it = query.iterate();   
        return it;   
    }   
}   
user的映射:User.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="usermap.User" table="users">   
    <id name="id">   
     <generator class="native"/>   
     </id>   
        <property name="name"/>   
        <property name="password"/>   
        <property name="email"/>   
    </class>   
</hibernate-mapping>   
 
hibernate全局配置: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>   
       
        <!-- 显示实际操作数据库时的SQL -->   
           
        <property name="show_sql">false</property>   
           
        <!-- SQL 方言,这边设定的是MySQL -->   
           
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>   
           
        <!-- JDBC 驱动程序 -->   
           
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>   
           
        <!-- JDBC URL 注意这边我设定的所使用的编码 -->   
           
        <property name="connection.url">jdbc:mysql://localhost:3306/myproject</property>   
           
        <!-- 数据库使用者 -->   
           
        <property name="connection.username">root</property>   
           
        <!-- 数据库密码 -->   
           
        <property name="connection.password">123456</property>   
           
        <!-- 以下设置对象与数据库表格映像文件 -->   
        <mapping resource="usermap/User.hbm.xml"/>   
       
    </session-factory>   
   
</hibernate-configuration>
 
测试网页:index.jsp
 
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ page import="usermap.User"%>
<%@ page import="usermap.UserBean"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
 UserBean ub=new UserBean();
 Iterator ii=ub.getAllUsers();
 
 int i=0;
 while(ii.hasNext()&&i<3){
  User u=(User)ii.next();
  out.print(u.getId()+u.getName()+"<br>");
  i++;
 }
  
%>
</body>
</html>


你可能感兴趣的:(Hibernate,String,user,iterator,insert,import)