Spring Data JPA 使用探究

這裏就濾過Spring Data JPA項目部署,不清楚的能夠看一下開源項目AutoAdminhtml

Entity(表實體類)

一個表對應一個實體類,這裏以AutoAdmin的sys_user表爲例:java

import cn.songhaiqing.autoadmin.base.BaseEntity;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;


@Entity
@Table(name = "sys_user")
@Where(clause = "deleted=0")
public class SysUser extends BaseEntity {
    // 帳號
    @Column(name = "account")
    private String account;
    // 密碼
    @Column(name = "password")
    private String password;
    // 姓名
    @Column(name = "name")
    private String name;
    // 密碼加密鹽
    @Column(name = "salt")
    private String salt;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }
}

備註git

  • @Table註解:寫表名,若是表是恰好使用駝峯命名的話能夠不寫,建議寫上。
  • @Where :查詢該表時會自動加個的條件,用來作軟刪除過濾是很是好的選擇,可是在@ManyToOne get該實體時若是數據已刪除就會有問題,注意區別使用。
  • @Column 字段申明,能夠寫在不一樣的位置,但我的習慣寫在字段上一行。屬性名能夠和數據庫表字段名不同。

BaseEntity
實體類繼承了BaseEntity,該類寫一些通用的字段,像ID、建立時間、更新時間、刪除標註等。github

import javax.persistence.*;
import java.util.Date;


@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "create_time", nullable = false,updatable = false)
    private Date createTime = new Date();

    @Column(name = "update_time", nullable = false)
    private Date updateTime = new Date();

    @Column(name = "deleted", nullable = false)
    private boolean deleted = false;

    public Date getCreateTime() {
        return createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Long getId() {
        return id;
    }

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

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public boolean isDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }
}

備註
* @Id @GeneratedValue(strategy = GenerationType.AUTO) ID 自增
* 默認值:直接給變量設置初始值就能夠了,create_time(建立時間)有點不同,由於我不想之後改變值,由於須要設置updatable = false。spring

Repository(表操做接口)

有人習慣叫DAO或其餘,JPA很重要的地方,使用JPA的語法簡單直接的替代了大部分SQL。數據庫

示例app

import cn.songhaiqing.autoadmin.entity.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface SysUserRepository extends JpaRepository<SysUser, Long>,JpaSpecificationExecutor<SysUser> {
    SysUser findByAccount(String account);

    long countByAccount(String account);

    long countByAccountAndIdNot(String account, Long id);
}

查詢

根據單查詢(一條結果)

SysUser findByAccount(String account);

須要確保返回的結果最多隻有一條,不然會報錯ide

根據單查詢(多條結果)

List<SysUser> findByAccount(String account);

多條件查詢

SysUser findByAccountAndPassword(String account, String password);

查詢第一條

SysUser findFirstByAccount(String account);

查詢前10條

SysUser findTop10ByAccount(String account);

排序

SysUser findTop10ByAccount(String account);

JPA語法

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname … where x.firstname = ?1
findByFirstnameIs
findByFirstnameEquals
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1(parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1(parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1(parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection ages) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

分頁複雜查詢

示例ui

List<Sort.Order> orders = new ArrayList<>();
orders.add(new Sort.Order(Sort.Direction.DESC,"id"));
Sort sort = new Sort(orders);
Page<SysUser> page = sysUserRepository.findAll(new Specification<SysUser>(){
    @Override
    public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicate = new ArrayList<>();
        // 此處添加過濾條件
        Predicate[] pre = new Predicate[predicate.size()];
        return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
    }
},new PageRequest(query.getPage() - 1, query.getLimit(),sort));
BaseResponseList<SysUserViewModel> result = new BaseResponseList<>();
result.setCount(page.getTotalElements());
List<SysUserViewModel> models = new ArrayList<>();
for (SysUser sysUser : page.getContent()) {
    SysUserViewModel model = new SysUserViewModel();
    model.setId(sysUser.getId());
    model.setAccount(sysUser.getAccount());
    model.setName(sysUser.getName());
    models.add(model);
}
result.setData(models);
return result;

此例中結合了分頁、排序、過濾功能。this

參考

相關文章
相關標籤/搜索