0

我是hibernate-spring tirple的新手..

我只是尝试编写简单的登记簿.. 我有以下代码:

学生.java

@Entity(name = "STUDENTS")
@NamedQueries({
    @NamedQuery(name = "getAllStudent", query = "SELECT k FROM STUDENTS k ORDER BY k.id DESC"),
    @NamedQuery(name = "findByName", query = "SELECT k FROM STUDENTS k WHERE k.name LIKE :name")
})
public class Student {

    @Column(name = "STUDENTNO", nullable = false)
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "NAME", nullable = false)
    private String name;
    @Column(name = "SURNAME")
    private String surname;
    @Column(name = "AGE")
    private String age;
    // GET ve SET metods

学生DAO.java

@Repository
@Transactional(readOnly = true)
public class StudentDAO implements IStudentDAO {

    @PersistenceContext
    EntityManager em;

    @Override
        public void deleteStudent(Student student) {
        Student temp = em.getReference(Student.class, student.getId());
        em.remove(temp);
        System.out.println("### getting out from studentDAO deleteStudent method ###")

StudentController.java

@Component
@Scope(value = "request")
public class StudentController {

@Autowired
IStudentDAO studentDAO;
List<Student> allStudentList = new ArrayList();
Student student = new Student();

@PostConstruct
 private void loadStudents() {
 allStudentList = studentDAO.allStudent();

 public void deleteStudent() {
 studentDAO.deleteStudent(student);
 System.out.println("### getting out from StudentController deleteStudent method ### ");
 }

当我运行deleteStudent()代码时,我得到:

"### 脱离 studentDAO deleteStudent 方法###"

"### 脱离 StudentController 的 deleteStudent 方法 ### "

我在输出中看到了这些,但没有从数据库中删除。我搜索了一下,发现“每个实体管理器的方法都打开自己的会话”。这就是为什么它说我应该像上面那样写我的 StudentDAO 的 deleteStudent 方法。

我想我错过了一些关于交易的东西,但我还没有意识到..

我该怎么办?

谢谢..

4

1 回答 1

0

@Transactional 注释在您的 DBMS 上创建一个事务。

如果您使用 (readOnly = true),您将阻止对数据库的操作(如 INSERT/UPDATE/DELETE)。

删除 readOnly = true 以便您的删除方法有效。

于 2013-11-12T12:03:42.747 回答