Hibernate4.3.10开发实例

pm45e 9年前

1、首先还是引入所需要的包


2、然后是配置hibernate.cfg.xml配置文件,连接mysql数据库信息,以及引入其他子模块的映射文件


<hibernate-configuration>  <session-factory>   <!-- 数据库连接信息 -->   <property name="show_sql">true</property>   <property name="connection.url">jdbc:mysql://localhost:3306/test</property>   <property name="connection.username">root</property>   <property name="connection.password">root</property>   <property name="connection.driver_class">com.mysql.jdbc.Driver</property>   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>   <property name="hbm2ddl.auto">update</property>      <mapping resource="/hibernateConfig/Login.hbm.xml" />  </session-factory>  </hibernate-configuration>

3、编写子模块的映射文件,这里是一个简单的登录信息表,Login.hbm.xml



<hibernate-mapping package="com.demo.model">        <class name="Login" table="login">          <id name="id" column="id">              <generator class="increment"/>          </id>          <property name="username" column="username" length="20"/>          <property name="password" column="password" length="20"/>      </class>    </hibernate-mapping>

4、编写model层的对象映射javabean,和普通的javabean没有什么大的区别,只是加了一些构造函数,属性和数据库表的字段对应



public class Login {   private int id;   private String username;   private String password;     (getter/setter)     public Login() {   }     public Login(int id, String username, String password) {    super();    this.id = id;    this.username = username;    this.password = password;   }  }

5、编写DAO层,DAO负责底层的数据库的一些操作,这里需要实现一个DAO接口,使得业务逻辑组件依赖DAO接口而不是具体实现类,将系统各组件之间的依赖提升到接口层次,避免类层次直接耦合(假如系统有所改变,只要接口层次没有改变,那么依赖该组件的上层组件也不需要改变,从而提供了良好的复用)


LoginDao接口:


public interface LoginDao {   public void saveLogin(Login login);     public void deleteLogin(Login login);     public void updateLogin(Login login);     public Login findLogin(int id);     public Login findLogin(String name);  }
LoginDaoImpl实现类:



public class LoginDaoImpl implements LoginDao {   public void deleteLogin(Login login) {    HibernateUtil.delete(login);   }     public Login findLogin(int id) {    return (Login) HibernateUtil.findById(Login.class, id);   }     public Login findLogin(String name) {    return (Login) HibernateUtil.findByName(name);   }     public void saveLogin(Login login) {    HibernateUtil.add(login);   }     public void updateLogin(Login login) {    HibernateUtil.update(login);   }  }

6、编写业务逻辑组件service,DAO已经帮我们实现了数据库的操作,在业务逻辑组件中我们则只需要调用DAO组件并关注于业务逻辑的实现即可


LoginService接口:


public interface LoginService {   public void save(Login login);     public void delete(Login login);     public void update(Login login);     public Login findById(int id);     public Login findByName(String name);  }
LoginServiceImpl实现类:



public class LoginServiceImpl implements LoginService {   private LoginDao loginDao;     public LoginDao getLoginDao() {    return loginDao;   }     public void setLoginDao(LoginDao loginDao) {    this.loginDao = loginDao;   }     public void delete(Login login) {    loginDao.deleteLogin(login);   }     public Login findById(int id) {    return loginDao.findLogin(id);   }     public Login findByName(String name) {    return loginDao.findLogin(name);   }     public void save(Login login) {    loginDao.saveLogin(login);   }     public void update(Login login) {    loginDao.updateLogin(login);   }  }

7、编写获取hibernate的SessionFactory类的工具类,这里编写一个简单的工具类,一般应用是在spring容器里来管理SessionFactory的



public class HibernateUtil {   private static SessionFactory sf;   static {    Configuration cfg = new Configuration();    cfg.configure("hibernateConfig/hibernate.cfg.xml");    sf = cfg.buildSessionFactory();   }     public static Session getSession() {    return sf.openSession();   }     public static void add(Object entity) {    Session session = null;    Transaction tx = null;    try {     session = HibernateUtil.getSession();     tx = session.beginTransaction();     session.save(entity);     tx.commit();    } catch (HibernateException e) {     e.printStackTrace();     throw e;    } finally {     if (session != null) {      session.close();     }    }   }     public static void delete(Object entity) {    Session session = null;    Transaction tx = null;    try {     session = HibernateUtil.getSession();     tx = session.beginTransaction();     session.delete(entity);     tx.commit();    } catch (HibernateException e) {     e.printStackTrace();     throw e;    } finally {     if (session != null) {      session.close();     }    }   }     public static void update(Object entity) {    Session session = null;    Transaction tx = null;    try {     session = HibernateUtil.getSession();     tx = session.beginTransaction();     session.update(entity);     tx.commit();    } catch (HibernateException e) {     e.printStackTrace();     throw e;    } finally {     if (session != null) {      session.close();     }    }   }     public static Object findById(Class clazz, Serializable id) {    Session session = null;    try {     session = HibernateUtil.getSession();     Object ob = session.get(clazz, id);     return ob;    } catch (HibernateException e) {     e.printStackTrace();     throw e;    } finally {     if (session != null) {      session.close();     }    }   }     public static Object findByName(String name) {    Session session = null;    try {     session = HibernateUtil.getSession();     Query query = session.createQuery("from test where name = :name");     query.setParameter("name", name);     Object ob = query.uniqueResult();     return ob;    } catch (HibernateException e) {     e.printStackTrace();     throw e;    } finally {     if (session != null) {      session.close();     }    }   }  }


注意:当hibernate.cfg.xml不放在src下时,在这里设置一下,让应用能找到这个配置文件


Configuration cfg = new Configuration();    cfg.configure("hibernateConfig/hibernate.cfg.xml");


8、action中调用业务逻辑组件提供一个保存用户名密码的实现


public String execute(){    Login login=new Login();    login.setUsername(getUsername());    login.setPassword(getPassword());    ls.save(login);    return SUCCESS;   }

9、在spring配置文件中配置一下各个bean,依赖注入一下



<bean id="loginDao" class="com.demo.dao.daoImpl.LoginDaoImpl" />   <bean id="loginService" class="com.demo.service.serviceImpl.LoginServiceImpl">    <property name="loginDao" ref="loginDao" />   </bean>   <bean id="registerAction" class="com.demo.action.RegisterAction"    scope="prototype">    <property name="ls" ref="loginService" />   </bean>

10、测试


一个简单的注册页面中输入用户名密码,点击注册后保存到数据库中


数据库中保存成功


来自:http://blog.csdn.net/kevinxxw/article/details/47145189