这里介绍Hibernate实例,increment可以在一个Hibernate实例的应用上很方便的时候,但是在集群的时候就不行了。

在向咱们具体介绍Hibernate实例之前,首先让咱们了解下Hibernate供给了多种生成主键的办法,然后全面介绍Hibernate实例。

简略叙述Hibernate实例(hibernate例子)  Hibernate实例 第1张

Hibernate(现在运用的版本是3.2)中供给了多种生成主键的办法。但是当时的这么多种生成办法未必能满意咱们的要求。比方increment,能够在一个Hibernate实例的应用上很便利的时分,但是在集群的时分就不行了。再如 identity ,sequence ,native 是数据局供给的主键生成办法,往往也不是咱们需求,并且在程序跨数据库方面也体现出缺乏。还有根据算法的生成办法生成出来的主键根本都是字符串的。

咱们现在需求一种生成办法:运用Long作为主键类型,主动增,支撑集群。那么咱们需求自定义一个咱们的主键生成器才干完成了。

Hibernate实例代码:

  1. packagehibernate;
  2. importjava.io.Serializable;
  3. importjava.sql.Connection;
  4. importjava.sql.PreparedStatement;
  5. importjava.sql.ResultSet;
  6. importjava.sql.SQLException;
  7. importjava.util.Properties;
  8. importorg.apache.commons.logging.Log;
  9. importorg.apache.commons.logging.LogFactory;
  10. importorg.hibernate.HibernateException;
  11. importorg.hibernate.MappingException;
  12. importorg.hibernate.dialect.Dialect;
  13. importorg.hibernate.engine.SessionImplementor;
  14. importorg.hibernate.id.Configurable;
  15. importorg.hibernate.id.IdentifierGenerator;
  16. importorg.hibernate.id.PersistentIdentifierGenerator;
  17. importorg.hibernate.type.Type;
  18. publicclassIncrementGeneratorimplementsIdentifierGenerator,Configurable{
  19. privatestaticfinalLoglog=LogFactory.getLog(IncrementGenerator.class);
  20. privateLongnext;
  21. privateStringsql;
  22. publicSerializablegenerate(SessionImplementorsession,Objectobject)
  23. throwsHibernateException{
  24. if(sql!=null){
  25. getNext(session.connection());
  26. }
  27. returnnext;
  28. }
  29. publicvoidconfigure(Typetype,Propertiesparams,Dialectd)
    throwsMappingException{
  30. Stringtable=params.getProperty("table");
  31. if(table==null)table=params.
    getProperty(PersistentIdentifierGenerator.TABLE);
  32. Stringcolumn=params.getProperty("column");
  33. if(column==null)column=params.
    getProperty(PersistentIdentifierGenerator.PK);
  34. Stringschema=params.getProperty
    (PersistentIdentifierGenerator.SCHEMA);
  35. sql="selectmax("+column+")from"+
    (
    schema==null?table:schema+'.'+table);
  36. log.info(sql);
  37. }
  38. privatevoidgetNext(Connectionconn)throwsHibernateException{
  39. try{
  40. PreparedStatementst=conn.prepareStatement(sql);
  41. ResultSetrs=st.executeQuery();
  42. if(rs.next()){
  43. next=rs.getLong(1)+1;
  44. }
  45. else{
  46. next=1l;
  47. }
  48. }catch(SQLExceptione)
  49. {
  50. thrownewHibernateException(e);
  51. }
  52. finally{
  53. try{
  54. conn.close();
  55. }catch(SQLExceptione)
  56. {
  57. thrownewHibernateException(e);
  58. }
  59. }
  60. }
  61. }

装备:
在对应的hbm文件里边将id的装备如下:

  1. <idname="id"type="long"column="id">
  2. <generatorclass="hibernate.IncrementGenerator"/>
  3. </id>

【修正引荐】

  1. Hibernate衔接装备办法分析
  2. Hibernate Session实例分析
  3. 浅析Hibernate Callback接口
  4. Hibernate Session缓存概述
  5. Hibernate修正addMate办法
转载请说明出处
知优网 » 简略叙述Hibernate实例(hibernate例子)

发表评论

您需要后才能发表评论