package cn.lihongjie.coal.base.dao;

import jakarta.persistence.criteria.Path;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

import java.util.List;

@NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T, String>, JpaSpecificationExecutor<T> {

    default T get(String id) {

        return findById(id).orElseThrow(() -> new RuntimeException("数据不存在: " + id));
    }

 

    default List<T> findByOrganizationId(String organizationId) {
        return findAll(
                (root, query, cb) -> {
                    try {

                        Path<Object> path = root.get("organizationId");
                        return cb.equal(path, organizationId);
                    } catch (Exception e) {
                        return cb.and();
                    }
                });
    }


    default void deleteByOrganizationId(String organizationId) {
         this.deleteAll(findAll(
                (root, query, cb) -> {
                    try {

                        Path<Object> path = root.get("organizationId");
                        return cb.equal(path, organizationId);
                    } catch (Exception e) {
                        return cb.and();
                    }
                }));
    }
}
