SpringBoot2.x-整合JPA一

码界捕手漫游
• 阅读 2803

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 发布
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Stella981 Stella981
3年前
ASMSupport教程4.7 生成关系运算符
<p在java中,关系运算符是很常用的,分别是&gt;,,&lt;,&gt;,&lt;,!这六种,我们按照惯例看看我们需要生成的代码:</p<divid"scid:9D7513F9C04C4721824A2B34F0212519:dfec0f1ca2ec4ebabc9b91c161fbfa47"class"wlWri
Stella981 Stella981
3年前
SpringBoot 2.0 系列002
SpringBoot2.0系列002运行流程分析SpringBoot2.0系列001入门介绍以及相关概念(https://my.oschina.net/lt0314/blog/1810336)1\.SpringBoot运行的几种方式
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
4,MongoDB 之 $关键字 及 $修改器 $set $inc $push $pull $pop MongoDB
MongoDB中的关键字有很多,$lt$gt$lte$gte等等,这么多我们也不方便记,这里我们说说几个比较常见的一.查询中常见的等于大于小于大于等于小于等于等于:在MongoDB中什么字段等于什么值其实就是":"来搞定比如"name":"路飞学城"!(https://oscimg.oschin
Stella981 Stella981
3年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Wesley13 Wesley13
3年前
MongoDB 范围查询
查询价格在2009000  $gt 大于   $lt  小于//查询价格2009000范围的数据db.prodgory.find({"price":{$gt:"200",$lt:"9000"}})查询给定范围数据  $in//给定范围查询db.product1.find({"categor
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
小万哥 小万哥
1年前
资源描述框架的用途及实际应用解析
RDF(资源描述框架)是一种用于机器理解网络资源的框架,使用XML编写。它通过URI标识资源,用属性描述资源,便于计算机应用程序处理信息。RDF在语义网上促进信息的确切含义和自动处理,使得网络信息可被整合。RDF语句由资源、属性和属性值组成。RDF文档包括&lt;rdf:RDF&gt;根元素和&lt;rdf:Description&gt;元素,后者用about属性标识资源。RDF还支持容器(如&lt;Bag&gt;、&lt;Seq&gt;和&lt;Alt&gt;)来描述集合。RDFS是RDF的扩展,提供描述类和属性的框架,而达布林核心是一组预定义属性,用于描述文档。
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(