Spring Hibernate删除对象

时间:2016-06-10 11:26:05

标签: java database spring hibernate

我尝试使用存储库中的“删除”从实体中删除对象,但有些东西不起作用。

@Entity
public class Director implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(length = 15)
    private String name;

    @Column(length = 40)
    private String surname;

    @Column(length = 40,unique=true, nullable=false)
    private String email;

    @Column(length = 12)
    private String phone;

    @OneToOne
    private School school;

    public School getSchool() {
        return school;
    }

    public void setSchool(School school) {
        this.school = school;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

存储库:

@Repository
public interface DirectorRepository extends CrudRepository<Director, Long> {

    Director findOneByEmail(String email);

}

来自Controller的方法:

@RequestMapping(value = "deleteDirector", method = RequestMethod.POST)
    public String delpost(@ModelAttribute Director director) {

        try {
            directorRepository.delete(director.getId());
            return "deleteDirectorSuccess-view";
        }
        catch(Exception e){

        }
        return "deleteDirectorError-view";
    }

我不知道那里发生了什么因为它返回deleteDirectorSuccess-view但是没有从数据库中删除这个对象(我确定id是正确的,我试过把directorRepository.delete(ID_FROM_DATABASE_AS_LONG);但是存在同样的问题。 如果我把脚本放在数据库中,如:

DELETE FROM public.director
 WHERE id=ID_FROM_DATABASE;

它工作,控制器中的另一种方法,我通过以下方式将对象保存到数据库:

directorRepository.save(director);

也很完美。

我不知道如何检查错误原因以及如何解决问题。

1 个答案:

答案 0 :(得分:0)

试试此代码

@RequestMapping(value = "deleteDirector", method = RequestMethod.POST)
@Transactional
public String delpost(@ModelAttribute Director director) {

    try {
        Director d = directorRepository.findOne(director.getId());
        directorRepository.delete(d);
        return "deleteDirectorSuccess-view";
    }
    catch(Exception e){

    }
    return "deleteDirectorError-view";
}

我认为实体需要在执行任何操作之前由持久层管理。但这并没有解释为什么保存工作。