请简述在JAVA Web应用开发中使用Hibernate操作数据库的步骤?

2025-03-03 18:53:14
推荐回答(3个)
回答1:

第一步:导入hibernate的jar包 到WEB-INF的lib下
第二步:在src目录下写一个hibernate.cfg.xml配置文件

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



true

jdbc:oracle:thin:@localhost:1521:ORCL

bsp

bsp

oracle.jdbc.OracleDriver

1

thread

org.hibernate.dialect.Oracle9Dialect

update



第三步:在src目录下建一个com.entity包,里面建一个Person类
package com.bsp.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {

private String id;
private String name;

@Id
@Column(length=10)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(length=10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

第四步:建一个测试类
package com.bsp.test;

import org.hibernate.Session;

import com.HibernateSessionFactory;

import junit.framework.TestCase;

public class TestBsp extends TestCase{

public void testSave() throws Exception {
Session session = HibernateSessionFactory.getSession();

session.close();
}
}
运行就可以自动在数据库里生成表了

回答2:

那只能是new了!
也可以使用多态扩充一下!
给你在这写一个例子,代码格式就不怎么讲究了:
1、直接new
首先可以写一个父类来方便获取Session

public Class HibernateSF{
// 这里面内容可以参考MyEclipse自动生成的SessionFactory静态类
public static Session getSession{
// 这里面的内容你自己写了
}
}

public Class StudentDao {

public List getStudents(){
// 这里面的内容你自己写了
}
}

然后struts的action里面直接
StudentDao sdao = new StudentDao()了 !

2、接口多态就是
public interface IStudentDao{

}
这样就是 IStudentDao sdao = new StudentDao();

建议学习Spring ,那样你会发现这个过程显得更简单了!

回答3:

1.Configuration conf = new Configuration().configure();
2.SessionFactory sf = conf.buildSessionFactory();
3.session = sf.openSession();
4.Transaction tx = session.beginTransaction();
5.session.save(class, serializable);
6.tx.commit();
7.session.close();

ps: 增删改需要 4. 6. 步 查询不需要