Spring Boot JPA to access the database

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45614509/article/details/101051420

Brief introduction

Before using Spring Data JPA's look at the differences between the JPA, Hibernate, Spring Data JPA three

The JPA (Java Persistence the API) is a specification the JPA itself, it is essentially a the ORM (object-relational mapping) specifications for Java object persistence data, and reads the management table in the database.

Hibernate belongs to follow an implementation of the JPA specification, but the JPA specification is one of Hibernate to follow, there are other specifications Hibernate implementation. Relationship is similar to the interface and implementation class

Spring Data JPA to provide a layer on the basis of realization Repository JPA specification, the re-encapsulation can be seen to JPA default use Hibernate as ORM implementation

After learning the basic situation to learn about the use of Spring Data JPA

integrated

I used environment is spring boot, add in the pom file

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

Or check when you create a spring boot SQL → JPA project

use

ready

Configuring a database connection

#通用数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useSSL=FALSE&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
# JPA 相关配置
# 自动建表时切换默认存储引擎 当前切换为InnoDB
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
#配置在日志中打印出执行的 SQL 语句信息
spring.jpa.show-sql=true
# 每次运行项目删除重建表
#spring.jpa.hibernate.ddl-auto=create
# hibernate懒加载相关,配置之后单元测试读取数据时不会报错
spring.jpa.open-in-view=true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Create a class

@Data                //lombok
@Entity              //必选注解
@Table(name = "user")//可选注解 如果不写name那么表明和类名一致
public class User {

    @Id                 //声明实体唯一标识的属性
    @GeneratedValue(strategy = GenerationType.IDENTITY) //sql自动生成主键
    private Long id;
    @Column(length = 50)//声明是一个字段, length声明字段长度
    private String name;
    @Column(length = 50)
    private String account;
    @Column(length = 50)
    private String password;

}
//JpaRepository是Repository的子接口 两个泛型分别为表的实体和主键
@Repository
public interface UserDao extends JpaRepository<User, Long> {

}

When we created the entity classes as long as you can access the database after creation UserDao, the first time I feel very easy to use

start using

Here is a simple CRUD use

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserTest {

    @Autowired
    private UserDao userDao;

    /**
     * 新增
     */
    @Test
    public void addUser() {
        User user = new User();
        user.setName("王二");
        user.setAccount("123");
        user.setPassword("1234256");
        userDao.save(user);
    }

    /**
     * 删除
     */
    @Test
    public void delete() {
        userDao.deleteById(3L);
    }

    /**
     * 修改
     * 修改使用的也是save,jpa判断是新增还是更新的方式主要是判断主键
     * 如果主键被赋值就会去数据库中查询是否有这条数据,如果存在就是更新,不存在就是创建
     * 更新时是全部字段的更新,如果有字段没有设置将会被赋值为null
     */
    @Test
    public void update() {
        User user = new User();
        user.setId(1L);
        user.setName("张三");
        user.setPassword("1221");
        userDao.save(user);
    }

    /**
     * 查询
     */
    @Test
    public void select() {
        User firstUser = userDao.getOne(1L);
        System.out.println(firstUser);
            
        Optional<User> s = userDao.findById(1L);
        s.ifPresent(System.out::println);


        User user = new User();
        user.setAccount("123"); //相当于查询 account 为123 的所有数据
        Example<User> userExample = Example.of(user);
        userDao.findAll(userExample);

        //排序按照id 倒序排序
        List<User> list = userDao.findAll(new Sort(Sort.Direction.DESC, "id"));
        for (User u : list) {
            System.out.println(u);
        }
    }

}

These systems provide the above method are, in fact, we can also follow the rules defined in the method in UserDao

@Repository
public interface UserDao extends JpaRepository<User, Long> {

    List<User> findByAccountEquals(String account);

}

Such JPA will be implemented as we follow the rules
image

idea Editor will prompt the appropriate method

Custom SQL statement

    /**
     * nativeQuery默认是false,nativeQuery为false是使用不知道是JPQL还是HQL (+﹏+)~晕
     * nativeQuery为true时是使用原生的sql语句,根据数据库的不同,sql语句可能有所区别
     */
    @Query(nativeQuery = true, value = "select  * from user where id in  :idList")
    List<User> findIdIn(@Param("idList") List<Long> idList);

    /**
     * 如果是删除或者是更新操作需要加上@Modifying注解以通知这是一个delete或update操作
     */
    @Modifying
    @Query(nativeQuery = true, value = "delete   from user where id =:id")
    void deleteById(@Param("id") Long id);

    /**
     * 执行insert 需要加上@Transactional和@Modifying两个注解
     */
    @Transactional
    @Modifying
    @Query(nativeQuery = true, value = "insert into jpa.user (name) values (:name)")
    void insert(@Param("name") String name);

Guess you like

Origin blog.csdn.net/weixin_45614509/article/details/101051420