参考书是孙卫琴的<精通Hibernate>
hibernate 3 + mysql 5.0
1 书上的例子第2章 初始化 hibernate Configuration实例
代码如下:
Configuration config = new Configuration();
config.addClass("Customer.class");
SessionFactory sessionfactory = config.buildSessionFactory();
配置文件是 hibernate.properties
运行出错 :提示为
org.hibernate.HibernateException: database product name cannot be null
显然是配置文件的问题
我用的配置文件是 hibernate.cfg.xml
修改为以下代码 成功运行
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
原因:使用了xm作为配置文件,而没有选择properties文件,应该使用new Configuration().config();
2 书上例子 第六章一对多映射
customer.hbm.xml 中
原代码为
<hibernate-mapping>
<class name="demo1.Customer" table="CUSTOMERS">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="NAME" length="15" />
</property>
</class>
</hibernate-mapping>
此时执行其Business.java时
Customer customer = (Customer) session.load(Customer.class,
new Long(customer_id));
出现如下错误
1Exception in thread "main" java.lang.NullPointerException
2 at org.hibernate.tuple.AbstractTuplizer.createProxy(AbstractTuplizer.java:249)
3 at org.hibernate.persister.entity.BasicEntityPersister.createProxy(BasicEntityPersister.java:2831)
4 at org.hibernate.event.def.DefaultLoadEventListener.createProxyIfNecessary(DefaultLoadEventListener.java:218)
5 at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:163)
6 at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:79)
7 at org.hibernate.impl.SessionImpl.load(SessionImpl.java:603)
8 at org.hibernate.impl.SessionImpl.load(SessionImpl.java:596)
修改为
<hibernate-mapping default-lazy="false">
<class name="demo1.Customer" table="CUSTOMERS">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="NAME" length="15" />
</property>
</class>
</hibernate-mapping>
问题解决
在Hibernate2.1中,lazy属性的默认值为“false”,而在Hibernate3.0中,lazy属性的默认值为“true”。