SpringBoot2.x-整合JPA一

pom.xml配置

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

application.properties配置

spring.datasource.url=jdbc:mysql://localhost:3306/v_chat?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456


# JPA配置
spring.jpa.database=mysql
# 在控制檯打印SQL
spring.jpa.show-sql=true
# 數據庫平臺
spring.jpa.database-platform=mysql
# 每次啓動項目時,數據庫初始化策略
spring.jpa.hibernate.ddl-auto=update
# 指定默認的存儲引擎爲InnoDB
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
#遇到大寫字母 加」_」的命名, 駝峯命名
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

實體類對象

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * <pre>
 * User -> 用戶實體類
 * </pre>
 *
 * @author 擼小魚
 * Copyright (c) lofish@foxmail.com
 */
@Entity(name = "t_user")
public class User{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String address;

    public Long getId(){
        return id;
    }

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

    public String getUsername(){
        return username;
    }

    public void setUsername( String username ){
        this.username = username;
    }

    public String getAddress(){
        return address;
    }

    public void setAddress( String address ){
        this.address = address;
    }
}

dao接口定義

import net.lofish.xpra.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * <pre>
 * UserDao -> dao層
 * </pre>
 *
 * @author 擼小魚
 * Copyright (c) lofish@foxmail.com
 */
public interface UserDao extends JpaRepository<User, Long>{

    List<User> getUserByAddressEqualsAndIdLessThanEqual( String address, Long id );
    
    //SQL nativeQuery的值是true 執行的時候不用再轉化
    @Query( value = "select * from t_user where id=(select max(id) from t_user)", nativeQuery = true )
    User maxIdUser();

}

測試

@SpringBootTest
class SpringbootXpraApplicationTests{


    @Autowired
    UserDao userDao;


    @Test
    void contextLoads(){
    }


    @Test
    void testUserDao(){
        userDao.getUserByAddressEqualsAndIdLessThanEqual( "abc", 1l );
    }

}

結果

Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.username as username3_0_ from t_user user0_ where user0_.address=? and user0_.id<=?

按照規範命名方法, jpa自動轉換層對應的查詢sql語句

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,findByFirstnameIs,findByFirstnameEquals" ... where x.firstname = ?1
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<Age> ages) ... where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> 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)

Repository接口

  • CrudRepository 提供CRUD的功能
  • PagingAndSortingRepository 提供分頁和排序功能
  • JpaRepository 提供JPA相關的方法,如刷新持久化數據、批量刪除
Spring Data中的每一個repository都繼承自Repository接口,可是,除此以外,它們每一個又有不一樣的功能

CrudRepository和PagingAndSortingRepository由Spring Data提供;JpaRepository 由Spring Data JPA提供,而Spring Data JPA又是Spring Data的一個子項目
,這就是二者的關係java

image

本文由博客羣發一文多發等運營工具平臺 OpenWrite 發佈
相關文章
相關標籤/搜索