锁定老帖子 主题:hibernate入门篇之新增功能!
该帖已经被评为精华帖
|
|
---|---|
作者 | 正文 |
发表时间:2003-12-19
javaIDE:eclipse 2.1.2 所有文件存放在:com.javamodel.hibernate目录下 Example.java package com.javamodel.hibernate; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import net.sf.hibernate.HibernateException; import net.sf.hibernate.MappingException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.Transaction; import net.sf.hibernate.cfg.Configuration; public class Example{ private static SessionFactory _sessions = null; private static Properties pops = new Properties();; static{ try { InputStream stream = Example.class.getResourceAsStream("hibernate.properties");; try { pops.load(stream);; } catch (IOException e1); { e1.printStackTrace();; } Configuration cfg = new Configuration();; cfg.addClass(Person.class);; cfg.setProperties(pops);; _sessions = cfg.buildSessionFactory();; } catch (MappingException e); { e.printStackTrace();; } catch (HibernateException e); { e.printStackTrace();; } } public static void main(String[] args); throws HibernateException { Person person = new Person();; person.setName("smallduzi");; person.setEmail("smallduzi@sohu.com");; Session session = _sessions.openSession();; Transaction tx = null; try{ tx = session.beginTransaction();; session.save(person);; tx.commit();; }catch(HibernateException he);{ if(tx != null); tx.rollback();; throw he; } finally{ session.close();; } } } Person.java package com.javamodel.hibernate; public class Person { private String id = null; private String name = null; private String email = null; public Person();{} /** * @return */ public String getEmail(); { return email; } /** * @return */ public String getId(); { return id; } /** * @return */ public String getName(); { return name; } /** * @param string */ public void setEmail(String string); { email = string; } /** * @param string */ public void setId(String string); { id = string; } /** * @param string */ public void setName(String string); { name = string; } } Person.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" > <hibernate-mapping> <class name="com.javamodel.hibernate.Person" table="person"> <id name="id"> <column name="id" length="40"/> <generator class="uuid.hex"/> </id> <property name="name" column="name" /> <property name="email" column="email" /> </class> </hibernate-mapping> hibernate.properties ## Oracle hibernate.dialect net.sf.hibernate.dialect.OracleDialect hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver hibernate.connection.username XXX hibernate.connection.password XXX #hibernate.connection.url jdbc:oracle:thin:@192.168.0.28:1521:orcl hibernate.connection.url jdbc:oracle:oci8:@XXX 我没有对他进行进一步的封装。那样初学者可能不理解。 注意:在工程里要引用hibernate的jar。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2003-12-20
InputStream stream = Example.class.getResourceAsStream("hibernate.properties");
这个语句是不是没有必要呢?我可以直接把hibernate.properties这个文件放在.\src目录下啊! |
|
返回顶楼 | |
发表时间:2003-12-22
条条大路通罗马,不是吗?^-^
例子中那样做是不是更灵活呢? |
|
返回顶楼 | |
发表时间:2003-12-25
InputStream stream = Example.class.getResourceAsStream("hibernate.properties");
quote] 这个函数是所有的配置文件都可以读进来么? 我没有用过 帮忙解答一下 |
|
返回顶楼 | |
发表时间:2003-12-25
相当于io一样,读文件。可以把"hibernate.properties" 启称别的名字如:hibernate_bak.properties等等。
|
|
返回顶楼 | |
发表时间:2003-12-29
这个例子相当简单,不过对不熟悉hibernate的朋友,应该还有一些难度(我本身就笨笨的),所以再向还没配置的朋友(大家应该都行吧),做一些解释。
1. 如果对DataBase不熟悉的朋友,可以在import net.sf.hibernate.cfg.Configuration;后面多import 一行: import net.sf.hibernate.tool.hbm2ddl.SchemaExport; // 这个是用来建立Table的。 ^^" 2. 在第30行,cfg.setProperties(pops); 后 加入 /* 这个是建立table的,第1次执行才需要跑,如果想要加入新的资料,此行必须remark起来(就是在前面加入//),否则将会将本来的table全部移除再建立1次....当然DataBase里头的资料也会全部砍光。 */ new SchemaExport(cfg).create(true, true); 3. hibernate.properties 这个档案在解压缩后的hibernate.jar里头的src里头可以找到,此例子必须把此档案放在和Example.class同一个folder。 4. Person.xml必须放在Person.class同一个folder。 我是在JBuilder里头执行此例子的,如果想要了解如何在JBuilder配置,请参考 十分钟在jb里面运行hibernate的简单例子。我是从这个例子开始进入hibernate的。感谢 getdown 兄。 也很感激 smallduzi 兄写了一系列 hibernate 的讲解。(smallduzi??....small=小,duzi=肚子,小肚子 兄??...开个玩笑...莫见怪... ^^") .................... |
|
返回顶楼 | |
发表时间:2003-12-29
感谢kitleong的补充!谢谢
|
|
返回顶楼 | |
发表时间:2004-01-15
我运行是提示错误:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment);. log4j:WARN Please initialize the log4j system properly. net.sf.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect. at net.sf.hibernate.dialect.Dialect.getDialect(Dialect.java:337); at net.sf.hibernate.dialect.Dialect.getDialect(Dialect.java:358); at net.sf.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:57); at net.sf.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:48); at com.javamodel.hibernate.Example.<clinit>(Example.java:31); java.lang.NullPointerException at com.javamodel.hibernate.Example.main(Example.java:47); Exception in thread "main" 应该怎样设置log4j; 另外配置hibernate.properties是是否除了自己需要的数据库,其它数据库设置都删除,都该保留哪些默认设置。 |
|
返回顶楼 | |
发表时间:2004-01-15
log4j 我没有设定,但是可以跑。hibernate.properties中,除了自己要的database之外,其他的可以用#remark起来。要删除也可以。
|
|
返回顶楼 | |
发表时间:2004-02-13
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" > <hibernate-mapping> <class name="com.hjtx.test.Person" table="person"> <id name="id" column ="id"> <generator class="identity"/> </id> <property name="name" column="name" type="string" length="100" /> <property name="email" column="email" type="string" length="100" /> </class> </hibernate-mapping> 我用sqlserver,出现问题是不能插入数据,出错信息是: 13:42:53,828 INFO Environment:432 - Hibernate 2.1.1 13:42:53,875 INFO Environment:466 - loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=com.microsoft.jdbc.sqlserver.SQLServerDriver, hibernate.cglib.use_reflection_optimizer=true, hibernate.cache.provider_class=net.sf.hibernate.cache.HashtableCacheProvider, hibernate.max_fetch_depth=1, hibernate.dialect=net.sf.hibernate.dialect.SybaseDialect, hibernate.jdbc.use_streams_for_binary=true, hibernate.jdbc.batch_size=0, hibernate.query.substitutions=true 1, false 0, yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.connection.username=sa, hibernate.connection.url=jdbc:microsoft:sqlserver://210.91.25.91:1433;DatabaseName=message, hibernate.connection.password=hjtx1234567, hibernate.connection.pool_size=1} 13:42:54,515 INFO Environment:480 - using java.io streams to persist binary types 13:42:54,531 INFO Environment:481 - using CGLIB reflection optimizer 13:42:54,546 INFO Configuration:318 - Mapping resource: com/hjtx/test/Message.hbm.xml 13:42:57,000 INFO Binder:225 - Mapping class: com.hjtx.test.Message -> Message 13:42:57,656 INFO Dialect:82 - Using dialect: net.sf.hibernate.dialect.SybaseDialect 13:42:57,687 INFO Configuration:584 - processing one-to-many association mappings 13:42:57,687 INFO Configuration:593 - processing one-to-one association property references 13:42:57,687 INFO Configuration:618 - processing foreign key constraints 13:42:58,312 INFO Configuration:584 - processing one-to-many association mappings 13:42:58,359 INFO Configuration:593 - processing one-to-one association property references 13:42:58,406 INFO Configuration:618 - processing foreign key constraints 13:42:58,421 INFO SchemaExport:98 - Running hbm2ddl schema export 13:42:58,421 INFO SchemaExport:117 - exporting generated schema to database 13:42:58,484 INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!) 13:42:58,484 INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 1 13:42:58,562 INFO DriverManagerConnectionProvider:71 - using driver: com.microsoft.jdbc.sqlserver.SQLServerDriver at URL: jdbc:microsoft:sqlserver://210.91.25.91:1433;DatabaseName=message 13:42:58,562 INFO DriverManagerConnectionProvider:72 - connection properties: {user=sa, password=hjtx1234567} drop table Message 13:42:59,718 DEBUG SchemaExport:132 - drop table Message 13:43:02,125 DEBUG SchemaExport:137 - Unsuccessful: drop table Message 13:43:02,125 DEBUG SchemaExport:138 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]无法 除去 表 'Message',因为它在系统目录中不存在。 create table Message ( MESSAGE_ID NUMERIC(19,0) IDENTITY NOT NULL, TEXT VARCHAR(100) not null, NEXT_MESSAGE VARCHAR(100) null, primary key (MESSAGE_ID) ) 13:43:02,125 DEBUG SchemaExport:149 - create table Message ( MESSAGE_ID NUMERIC(19,0) IDENTITY NOT NULL, TEXT VARCHAR(100) not null, NEXT_MESSAGE VARCHAR(100) null, primary key (MESSAGE_ID) ) 13:43:02,171 INFO SchemaExport:160 - schema export complete 13:43:02,171 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:02,171 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to message 13:43:02,171 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:02,171 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将数据库上下文改为 'message'。 13:43:02,187 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:02,187 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC]Language changed to 简体中文 13:43:02,187 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:02,187 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将语言设置改为 简体中文。 13:43:02,187 INFO DriverManagerConnectionProvider:137 - cleaning up connection pool: jdbc:microsoft:sqlserver://210.91.25.91:1433;DatabaseName=message 13:43:02,203 INFO Configuration:584 - processing one-to-many association mappings 13:43:02,203 INFO Configuration:593 - processing one-to-one association property references 13:43:02,203 INFO Configuration:618 - processing foreign key constraints 13:43:02,234 INFO Dialect:82 - Using dialect: net.sf.hibernate.dialect.SybaseDialect 13:43:02,234 INFO SettingsFactory:58 - Maximim outer join fetch depth: 1 13:43:02,250 INFO SettingsFactory:62 - Use outer join fetching: true 13:43:02,250 INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!) 13:43:02,250 INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 1 13:43:02,250 INFO DriverManagerConnectionProvider:71 - using driver: com.microsoft.jdbc.sqlserver.SQLServerDriver at URL: jdbc:microsoft:sqlserver://210.91.25.91:1433;DatabaseName=message 13:43:02,250 INFO DriverManagerConnectionProvider:72 - connection properties: {user=sa, password=hjtx1234567} 13:43:02,281 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of process level read-write cache is not recommended) 13:43:02,562 INFO SettingsFactory:89 - Use scrollable result sets: true 13:43:02,562 INFO SettingsFactory:99 - Query language substitutions: {no='N', true=1, yes='Y', false=0} 13:43:02,562 INFO SettingsFactory:110 - cache provider: net.sf.hibernate.cache.HashtableCacheProvider 13:43:02,562 INFO Configuration:1057 - instantiating and configuring caches 13:43:03,000 INFO SessionFactoryImpl:119 - building session factory 13:43:04,250 INFO SessionFactoryObjectFactory:82 - no JNDI name configured 13:43:04,500 INFO DriverManagerConnectionProvider:137 - cleaning up connection pool: jdbc:microsoft:sqlserver://210.91.25.91:1433;DatabaseName=message 13:43:04,703 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:04,703 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to message 13:43:04,703 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:04,718 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将数据库上下文改为 'message'。 13:43:04,718 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:04,718 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC]Language changed to 简体中文 13:43:04,718 WARN JDBCExceptionReporter:20 - SQL Warning: 0, SQLState: 13:43:04,718 WARN JDBCExceptionReporter:28 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将语言设置改为 简体中文。 类文件: package com.hjtx.test; import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.tool.hbm2ddl.SchemaExport; import net.sf.hibernate.Session; import net.sf.hibernate.Query; import net.sf.hibernate.Hibernate; import net.sf.hibernate.type.LongType; import net.sf.hibernate.Transaction; import net.sf.hibernate.HibernateException; public class test { public test() { } public static void main(String args[]) throws Exception { Configuration cfg = new Configuration().addClass(Message.class); new SchemaExport(cfg).create(true, true); SessionFactory sessions = cfg.buildSessionFactory(); Session session = sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Message message = new Message(); message.setText("liujun"); message.setNextMessage("mynextmeaage"); session.save(message); tx.commit(); } catch (HibernateException ex) { tx.rollback(); } session.close(); } } 请赐教,谢谢! |
|
返回顶楼 | |