这里介绍Hibernate实例,increment可以在一个Hibernate实例的应用上很方便的时候,但是在集群的时候就不行了。
在向咱们具体介绍Hibernate实例之前,首先让咱们了解下Hibernate供给了多种生成主键的办法,然后全面介绍Hibernate实例。
Hibernate(现在运用的版本是3.2)中供给了多种生成主键的办法。但是当时的这么多种生成办法未必能满意咱们的要求。比方increment,能够在一个Hibernate实例的应用上很便利的时分,但是在集群的时分就不行了。再如 identity ,sequence ,native 是数据局供给的主键生成办法,往往也不是咱们需求,并且在程序跨数据库方面也体现出缺乏。还有根据算法的生成办法生成出来的主键根本都是字符串的。
咱们现在需求一种生成办法:运用Long作为主键类型,主动增,支撑集群。那么咱们需求自定义一个咱们的主键生成器才干完成了。
Hibernate实例代码:
- packagehibernate;
- importjava.io.Serializable;
- importjava.sql.Connection;
- importjava.sql.PreparedStatement;
- importjava.sql.ResultSet;
- importjava.sql.SQLException;
- importjava.util.Properties;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- importorg.hibernate.HibernateException;
- importorg.hibernate.MappingException;
- importorg.hibernate.dialect.Dialect;
- importorg.hibernate.engine.SessionImplementor;
- importorg.hibernate.id.Configurable;
- importorg.hibernate.id.IdentifierGenerator;
- importorg.hibernate.id.PersistentIdentifierGenerator;
- importorg.hibernate.type.Type;
- publicclassIncrementGeneratorimplementsIdentifierGenerator,Configurable{
- privatestaticfinalLoglog=LogFactory.getLog(IncrementGenerator.class);
- privateLongnext;
- privateStringsql;
- publicSerializablegenerate(SessionImplementorsession,Objectobject)
- throwsHibernateException{
- if(sql!=null){
- getNext(session.connection());
- }
- returnnext;
- }
- publicvoidconfigure(Typetype,Propertiesparams,Dialectd)
throwsMappingException{- Stringtable=params.getProperty("table");
- if(table==null)table=params.
getProperty(PersistentIdentifierGenerator.TABLE);- Stringcolumn=params.getProperty("column");
- if(column==null)column=params.
getProperty(PersistentIdentifierGenerator.PK);- Stringschema=params.getProperty
(PersistentIdentifierGenerator.SCHEMA);- sql="selectmax("+column+")from"+
(schema==null?table:schema+'.'+table);- log.info(sql);
- }
- privatevoidgetNext(Connectionconn)throwsHibernateException{
- try{
- PreparedStatementst=conn.prepareStatement(sql);
- ResultSetrs=st.executeQuery();
- if(rs.next()){
- next=rs.getLong(1)+1;
- }
- else{
- next=1l;
- }
- }catch(SQLExceptione)
- {
- thrownewHibernateException(e);
- }
- finally{
- try{
- conn.close();
- }catch(SQLExceptione)
- {
- thrownewHibernateException(e);
- }
- }
- }
- }
装备:
在对应的hbm文件里边将id的装备如下:
- <idname="id"type="long"column="id">
- <generatorclass="hibernate.IncrementGenerator"/>
- </id>
【修正引荐】
- Hibernate衔接装备办法分析
- Hibernate Session实例分析
- 浅析Hibernate Callback接口
- Hibernate Session缓存概述
- Hibernate修正addMate办法
转载请说明出处
知优网 » 简略叙述Hibernate实例(hibernate例子)
知优网 » 简略叙述Hibernate实例(hibernate例子)