Springboot中jpa的基本使用

临近毕业,找了一份java实习生的工作,刚进公司,也没有立即给我任务,老师给了我一份博客让我学着,学了几天的jpa的基本使用和MyBatis-Plus的基本使用,总结如下:
springboot博客学习地址:
http://www.ityouknow.com/spring-boot.html

jpa的基本使用:
第一步:
添加依赖

<dependency>
 <groupId>org.Springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
</dependency>

第二步:
在application.properties中添加配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnico
de=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#SQL 输出
spring.jpa.show-sql=true
#format ⼀下 SQL 进⾏输出
spring.jpa.properties.hibernate.format_sql=true

关键参数:hibernate.hbm2ddl.auto 参数主要包含三个create,update,valiate。
create:每次加载时将上一张表删除重新创建新表。
update:每次加载更新第一次加载Hibernate时根据实体类创建的表。
validate :每次加载 Hibernate 时,验证创建数据库表结构,只会和数据库中的表进⾏⽐较,不会创建
新表,但是会插⼊新值.

实体类:

package com.wuf.jpa.pojo;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;


@Entity
@NamedQueries({
        @NamedQuery(name = "User.findByPassWord", query = "select u from User u where u.passWord = ?1"),
        @NamedQuery(name = "User.findByNickName", query = "select u from User u where u.nickName = ?1"),
})
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private String regTime;


    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    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 getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getRegTime() {
        return regTime;
    }

    public void setRegTime(String regTime) {
        this.regTime = regTime;
    }

    public User(String username, String password, String email, String nickName, String regTime) {
        this.userName = username;
        this.passWord = password;
        this.email = email;
        this.nickName = nickName;
        this.regTime = regTime;


    }

    public User(Long id,String username, String password, String email, String nickName, String regTime) {
        this.id = id;
        this.userName = username;
        this.passWord = password;
        this.email = email;
        this.nickName = nickName;
        this.regTime = regTime;
    }


    public User() {
        super();
    }

}

http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html
下⾯对上⾯⽤的注解做⼀个解释。
@Entity(name=“EntityName”) 必须,⽤来标注⼀个数据库对应的实体,数据库中创建的表名默
认和类名⼀致。其中,name 为可选,对应数据库中⼀个表,使⽤此注解标记 Pojo 是⼀个 JPA 实体。
@Table(name="",catalog="",schema="") 可选,⽤来标注⼀个数据库对应的实体,数据库
中创建的表名默认和类名⼀致。通常和 @Entity 配合使⽤,只能标注在实体的 class 定义处,表示实体
对应的数据库表的信息。
@Id 必须,@Id 定义了映射到数据库表的主键的属性,⼀个实体只能有⼀个属性被映射为主键。
@GeneratedValue(strategy=GenerationType,generator="") 可选,strategy: 表示主键
⽣成策略,有 AUTO、INDENTITY、SEQUENCE 和 TABLE 4 种,分别表示让 ORM 框架⾃动选择,
generator: 表示主键⽣成器的名称。
@Column(name = “user_code”, nullable = false, length=32) 可选,@Column 描
述了数据库表中该字段的详细定义,这对于根据 JPA 注解⽣成数据库表结构的⼯具。name: 表示数据库
表中该字段的名称,默认情形属性名称⼀致;nullable: 表示该字段是否允许为 null,默认为 true;
unique: 表示该字段是否是唯⼀标识,默认为 false;length: 表示该字段的⼤⼩,仅对 String 类型的字段
有效。
@Transient 可选,@Transient 表示该属性并⾮⼀个到数据库表的字段的映射,ORM 框架将忽略该
属性。
@Enumerated 可选,使⽤枚举的时候,我们希望数据库中存储的是枚举对应的 String 类型,⽽不是
枚举的索引值,需要在属性上⾯添加 @Enumerated(EnumType.STRING) 注解。

根据上面的注解在使用时jpa会自动在数据库中生成我们需要的表。

在dao层新建一个UserRepository类,继承JpaRepository<User, Long>

public interface UserRepository extends JpaRepository<User, Long>{}

这时就可以使用它最基本的几个用法,我们写一个测试类

	@Test
    public void testSave() throws Exception {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String formattedDate = dateFormat.format(date);

        UserRepository.save(new User("aa", "aa123456","aa@126.com", "aa",  formattedDate));
       
    }

基本功能包含

@Test
public void testBaseQuery() {
 userRepository.findAll();
 userRepository.findById(1l);
 userRepository.save(user);
 userRepository.delete(user);
 userRepository.count();
 userRepository.existsById(1l);
 // ...
}

另外我们也可以在UserRepository类利用关键字添加我们需要的方法

User findByUserName(String userName);

具体关键字大家可以看这个博客

jpa的基本使用

查询函数的基本使用最关键的有一个分页查询,jpa直接提供了一个Pageable参数,在方法中作为最后一个参数传入

	int page=1,size=10;
	Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值