SpringBoot和JPA整合

项目结构: 

SpringBoot和JPA整合_第1张图片

pom.xml:



    4.0.0

    com.Lucifer.pringboot
    springboot-jpa
    0.0.1-SNAPSHOT
    jar

    springboot-jpa
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

    show-sql: true
开启驼峰命名:
spring.hibernate.naming.physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

如果不开启的话,查询的lastname是null,因为表中字段是last_name,需要开启驼峰命名规则。

spring.jpa.show-sql: true 打印sql语句。

User实体类:

package com.lucifer.springboot.jpa.entity;

import javax.persistence.*;

/**
 * @author: Lucifer
 * @create: 2018-09-20 16:21
 * @description:
 **/

/*
    使用JPA注解配置映射关系
    @Entity 告诉jpa这是一个实体类(和数据库表映射的类)
    @Table 指定和哪个数据表对应;如果省略name,默认表名是user
 */

@Entity
@Table(name = "tbl_user")
public class User {

    /**
     * 自增主键id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "last_name", length = 50)//这是和数据表对应的一个列
    private String lastname;

    /**
     * 省略默认列名就是属性名
     */
    @Column
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
UserRepository接口:
package com.lucifer.springboot.jpa.repository;

import com.lucifer.springboot.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 继承JpaRepository来完成对数据库表的操作
 */
public interface UserRepository extends JpaRepository {


}

查看JpaRepository接口源码,可以发现里面有很多对于数据库表增删改查操作的接口。

/*
 * Copyright 2008-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.jpa.repository;

import java.util.List;

import javax.persistence.EntityManager;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;

/**
 * JPA specific extension of {@link org.springframework.data.repository.Repository}.
 *
 * @author Oliver Gierke
 * @author Christoph Strobl
 * @author Mark Paluch
 */
@NoRepositoryBean
public interface JpaRepository extends PagingAndSortingRepository, QueryByExampleExecutor {

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.CrudRepository#findAll()
	 */
	List findAll();

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
	 */
	List findAll(Sort sort);

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.CrudRepository#findAll(java.lang.Iterable)
	 */
	List findAllById(Iterable ids);

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
	 */
	 List saveAll(Iterable entities);

	/**
	 * Flushes all pending changes to the database.
	 */
	void flush();

	/**
	 * Saves an entity and flushes changes instantly.
	 *
	 * @param entity
	 * @return the saved entity
	 */
	 S saveAndFlush(S entity);

	/**
	 * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear
	 * the {@link javax.persistence.EntityManager} after the call.
	 *
	 * @param entities
	 */
	void deleteInBatch(Iterable entities);

	/**
	 * Deletes all entities in a batch call.
	 */
	void deleteAllInBatch();

	/**
	 * Returns a reference to the entity with the given identifier.
	 *
	 * @param id must not be {@literal null}.
	 * @return a reference to the entity with the given identifier.
	 * @see EntityManager#getReference(Class, Object)
	 * @throws javax.persistence.EntityNotFoundException if no entity exists for given {@code id}.
	 */
	T getOne(ID id);

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)
	 */
	@Override
	 List findAll(Example example);

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
	 */
	@Override
	 List findAll(Example example, Sort sort);
}
SpringbootJpaApplication启动类:
package com.lucifer.springboot.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootJpaApplication.class, args);
    }
}
UserController:
package com.lucifer.springboot.jpa.controller;

import com.lucifer.springboot.jpa.entity.User;
import com.lucifer.springboot.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author: Lucifer
 * @create: 2018-09-20 17:10
 * @description:
 **/
@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;


    @GetMapping("/insert")
    public User insertuser(User user){
        User save = userRepository.save(user);
        return save;
    }

    @GetMapping(value = "/user/{id}")
    public User getuser(@PathVariable("id") Integer id){
        User user = userRepository.findById(id).get();
        return user;
    }
}

ps:查看源码,findById(ID id)这个方法是Optional接收的。

SpringBoot和JPA整合_第2张图片

 而UserController类中的getuser方法是用user来接收的,所以可以直接

User user = userRepository.findById(id);

下图可能更容易理解:

SpringBoot和JPA整合_第3张图片

源码:

SpringBoot和JPA整合_第4张图片

如果数据库表中为空,没有数据,执行查询会报错。

SpringBoot和JPA整合_第5张图片

因此查询之前,有必要做个非空判断的。

最后------》

在浏览器中输入请求,执行对应的sql语句,打印在控制台,此时整合成功!!!!

 

 

 

你可能感兴趣的:(SpringBoot技术篇)