public class Student {
private int id;
private String name;
private int age;
}
public interface StudentDAO {
void addStudent(Student student);
void updateStudent(Student student);
void deleteStudent(int id);
Student getStudentById(int id);
List<Student> getAllStudents();
}
public class HibernateStudentDAOImpl implements StudentDAO {
@Override
public void addStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(student);
transaction.commit();
session.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
public class Main {
public static void main(String[] args) {
StudentDAO studentDAO = new HibernateStudentDAOImpl();
studentDAO.addStudent(student1);
Student student2 = studentDAO.getStudentById(1);
student2.setAge(21);
studentDAO.updateStudent(student2);
studentDAO.deleteStudent(1);
}
}