JpaRepository主要用于数据库数据查询,在springboot的项目中,有如下使用场景:
首先,针对数据库的某张业务表创建一个实体类。需要使用注解声明,与表对应。如果是存储在es,使用
@Document(indexName = "big_log")
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author l 2021/4/28
*/
@Entity
@Table(
name = "T_Alarm"
)
@Component
@Scope("prototype")
public class BigEntity extends BaseBean implements Serializable {
private static final long serialVersionUID = 1325859442141576908L;
@Id
@GeneratedValue(
strategy = GenerationType.AUTO
)
@Column(
name = "ID"
)
private Integer id;
@Column(
length = 50,
nullable = false,
name = "ObjectID"
)
private String objectID;
@Column(
length = 50,
nullable = false,
name = "ObjectType"
)
private String objectType;
//getters and setters...
}
然后在dao层增加对这个实体类的查询方法。
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author l 2021/4/28
*/
public interface IBigDao extends JpaRepository<BigEntity, Long>, JpaSpecificationExecutor<BigEntity> {
/**
* 根据内容查询
*
* @param alarmContent 文本
* @return BigEntity唯一实体
*/
BigEntity findByAlarmContentAndAlarmState(String alarmContent, EAlarmState alarmState);
}
然后在service层就可以针对这个实体类操作数据了,在方法或者类(推荐方法)上加注解
@Transactional(rollbackFor = Exception.class)
相当于开始一个事务,然后对获取到的实体对象进行更新(若返回为空则新增),最后调用save方法。
@Resource private IBigDataToAlarmTableDao bigDataToAlarmTableDao;
@Transactional(rollbackFor = Exception.class) public Result receiveReportData(LogReportReq reportData)
{
bigDataToAlarmTableDao.save(bigDataToAlarmTableEntity);
}