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的一个子项目

,这就是两者的关系

SpringBoot2.x-整合JPA一

本文由博客群发一文多发等运营工具平台 OpenWrite 发布

原文 

https://segmentfault.com/a/1190000022308656

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » SpringBoot2.x-整合JPA一

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址