JpaRepository初使用

本文介绍了如何使用JpaRepository在Spring应用中操作数据库。首先创建与业务表对应的实体类,并使用注解进行声明。接着在DAO层定义查询方法,然后在Service层进行事务控制,通过save方法实现数据的增删改查操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值