Hibernate和JPA @PreUpdate和@PrePersist无法正常工作

时间:2019-06-03 05:07:37

标签: spring hibernate jpa

我正试图在更新或保存之前运行一些代码。我在我的实体中:

                     0      admin1            admin2
0 -2322251069948147489   Minnesota    Carlton County
1 -2542975094649810558  California       Yolo County
2 -1984478776812705270    Virginia  Arlington County
3 -2720329071386930320        Iowa       Polk County

我在FileManagementRepository中:

@Data
@EqualsAndHashCode(callSuper=false)
@Table(name="file_management", uniqueConstraints = { @UniqueConstraint(columnNames = {"name"})})
@Entity
public class FileManagement {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;

    @Column(name="name")
    private String name;

    @Column(name = "SEARCH_STRING", length = 1000)
    @Getter @Setter
    private String searchString;

    @PreUpdate
    @PrePersist
    void updateSearchString() {

        final String fullSearchString = StringUtils.join(Arrays.asList(
                name),
                " ");

        this.searchString = StringUtils.substring(fullSearchString, 0, 999);

    }
}

和我的FileManagementService.java

    @Transactional
    @Modifying
    @Query("UPDATE FileManagement SET name = :name WHERE id = :id")
    public void updateFile(long id, String name);

    @Transactional
    @Modifying
    @Query(value = "INSERT INTO file_management (name, filename, created_by, create_date, is_active, is_deleted) VALUES (:name, :filename, :createdBy, :createdDate, :isActive, :isDeleted)", nativeQuery = true)
    public void createFileWithFilename(String name, String filename, String createdBy, Date createdDate, boolean isActive, boolean isDeleted);

但是问题是我更新或插入新行时未调用updateSearchString()方法。 search_string列为(null)

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

我猜测以这种方式使用本机SQL或JPQL插入或更新的实体将通过持久性上下文,而持久性上下文将无法管理它们。但是,@PreUpdate@PrePersist仅适用于由持久性上下文管理的实体,因此您的@PreUpdate@PrePersist不会对其执行。

我认为您应该以更加JPA的方式插入和更新实体,以确保持久性上下文将对它们进行管理:

@Service
public class FileManagementService{

    @Autowired
    private FileManagementRepository fileManagementRepository;

    @Transactional 
    public void updateFileWithFilename(String id, String name) {
       Optional<FileManagement> file= fileManagementRepository.findById(id);
       if(file.isPresent()){
           file.get().setName(name);
       }else{
          throw new RuntimeException("Record does not exist");
       }
    }

    @Transactional 
    public void createFileWithFilename(String name, String filename, String createdBy, Date createdDate, boolean isActive, boolean isDeleted) {
       FileManagement file= new FileManagement(name,fileName,........);
       fileManagementRepository.save(file);
    }
}