-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentService.java
More file actions
89 lines (79 loc) · 2.93 KB
/
StudentService.java
File metadata and controls
89 lines (79 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package sba.sms.services;
import lombok.extern.java.Log;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import sba.sms.dao.StudentI;
import sba.sms.models.Course;
import sba.sms.models.Student;
import sba.sms.utils.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
/**
* StudentService is a concrete class. This class implements the
* StudentI interface, overrides all abstract service methods and
* provides implementation for each method. Lombok @Log used to
* generate a logger file.
*/
public class StudentService implements StudentI {
@Override
public void createStudent(Student student) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
@Override
public List<Student> getAllStudents() {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Student", Student.class).list();
}
}
@Override
public Student getStudentByEmail(String email) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.get(Student.class, email);
}
}
@Override
public boolean validateStudent(String email, String password) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Student student = session.get(Student.class, email);
return student != null && student.getPassword().equals(password);
}
}
@Override
public void registerStudentToCourse(String email, int courseId) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Student student = session.get(Student.class, email);
Course course = session.get(Course.class, courseId);
if (student != null && course != null) {
student.getCourse().add(course);
session.saveOrUpdate(student);
}
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
public List<Course> getStudentCourses(String email) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Student student = session.get(Student.class, email);
return new ArrayList<>(student.getCourse());
}
}
}