示例1:创建实体类和映射
import javax.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
// Getters and setters
}
在示例1中,我们创建了一个名为Student的实体类,并使用注解定义了表名、字段名以及主键的生成策略。该实体类对应数据库中的"students"表,包含id、name和age三个字段。
示例2:配置Hibernate会话工厂
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// 加载Hibernate配置文件
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
return configuration.buildSessionFactory();
} catch (Exception ex) {
System.err.println("SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
在示例2中,我们创建了一个HibernateUtil类,该类负责配置Hibernate的会话工厂(SessionFactory)。会话工厂是与数据库交互的主要入口点。
示例3:使用Hibernate进行数据操作
import org.hibernate.Session;
import org.hibernate.Transaction;
public class StudentDAO {
public void saveStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
}
public Student getStudentById(Long id) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
return session.get(Student.class, id);
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
session.close();
}
}
public void updateStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(student);
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
}
public void deleteStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.delete(student);
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
}
}
在示例3中,我们创建了一个StudentDAO类,该类负责对Student实体进行增删改查操作。通过打开会话(Session)并在事务(Transaction)中执行相应的操作,我们可以保存、获取、更新和删除学生对象。
请注意,在示例3中,我们通过HibernateUtil类获取会话工厂,并使用会话工
厂打开会话。在每个操作完成后,我们需要关闭会话以释放资源。
标签:transaction,实例,示例,session,Hibernate,Student,使用,public,ex From: https://www.cnblogs.com/lukairui/p/17443891.html