1 。建立数据库
Database:mysql
drop database if exists SAMPLEDB;
create database hello;
use hello;
create table CUSTOMERS (
ID int not null primary key,
NAME varchar(15) not null,
PASSWORD varchar(8) not null
);
2。在eclipse 中新建工程hbtest
3。在src中新建package hbm
4。新建pojo类Customer
package hbm;
public class Customer {
private int id;
private String name;
private String password;
/**
* @return Returns the id.
*/
public int getId() {
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(int id) {
this.id = id;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name
* The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password
* The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
//constructor
public Customer() {
}
}
5。使用myeclipse插件建立hibernate.cfg.xml 位于src目录下
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hello</property>
<property name="myeclipse.connection.profile">hbmysql</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<mapping resource="hbm/Customer.hbm.xml" />
</session-factory>
</hibernate-configuration>
6。在hbm package内新建Customer.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-mapping>
<class name="hbm.Customer" table="CUSTOMERS">
<id name="id" column="ID" type="int">
<generator class="increment"/>
</id>
<property name="name" column="NAME" type="string" not-null="true"/>
<property name="password" column="PASSWORD" type="string" not-null="true"/>
</class>
</hibernate-mapping>
7。使用hibernate操作数据库
package hbm;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.Iterator;
import java.util.List;
public class Hbmain {
public static SessionFactory sessionFactory;//数据存储源
static {
try {
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 将一个customer对象存入database
* @Customer customer Object
*/
public void saveCustomer(Customer ct) {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(ct);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/*
* 查找所有的customer object
*/
public void findAll() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List customers = session.createQuery(
"from Customer as c order by c.name asc").list();
Iterator it = customers.iterator();
System.out.println("append:"+customers.size());
while(it.hasNext())
{
Customer c = (Customer)it.next();
System.out.println("ID:" + c.getId());
System.out.println("Name:" + c.getName());
System.out.println("Pass:" + c.getPassword());
}
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}
}
/*
* 修改customer Name
* @name
*/
public void loadUpdate(int customer_id, String name) {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer c = (Customer) session.load(Customer.class, customer_id);
c.setName(name);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
/*
* 测试以上的方法
* save() find() update()
*/
public void test()
{
Customer ct = new Customer();
//ct.setId(5);
ct.setName("buaa");
ct.setPassword("5768");
this.saveCustomer(ct);
this.findAll();
this.loadUpdate(ct.getId(),"phop");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Hbmain hb = new Hbmain();
hb.test();
sessionFactory.close();
}
}
初学hibernate遇到的几个问题的解决
参考书是孙卫琴的<精通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));
出现如下错误
1 Exception 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>
问题解决
原因在于: Hibernate 3.0 与Hibernate2.1的源代码是不兼容的
在Hibernate2.1中,lazy属性的默认值为“false”,而在Hibernate3.0中,lazy属性的默认值为“true”。
posted on 2007-10-10 20:52
谭明 阅读(1622)
评论(0) 编辑 收藏 所属分类:
Hibernate