xl_echo编辑整理,交流学习请加1280023003 百战不败,依不自称常胜,百败不颓,依能奋力前行。——这才是真正的堪称强大!!
Spring Data JPA 可以理解为JPA规范的再次封装抽象,底层还是使用了Hibernate
的JPA技术实现,引用JPQL(Java Persistence Query Language)查
询语言,属于Spring整个生态体系的一部分。
Spring Data JPA的主要特征
- 提供模板操作,如Spring Data Redis和Spring Data Riak。
- 强大的Repository和定制的数据存储对象的抽象映射。
- 对数据访问对象的支持(Auting等)。
结合MySQL和springboot工程,我们快速认识JPA
搭建一个简单的springboot工程,引入MySQL和Web、JPA三个依赖(本工程还是用idea插件lombok)。
项目结构如下:
快速搭建controller、repository和entity层,在properties中配置连接数据的基本设置。本项目设置如下
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=123456
在数据库创建一个user表
CREATE TABLE user (
id int(11) not null AUTO_INCREMENT,
name varchar(50) default null,
email varchar(200) default null,
PRIMARY KEY(id)
)
对应表创建一个User实体类
package com.echo.example.example.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* author:XLecho
* Date:2018/10/25 0025
* Time:19:07
*/
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String email;
}
完成repository构建
package com.echo.example.example.repository;
import com.echo.example.example.entity.User;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* author:XLecho
* Date:2018/10/25 0025
* Time:19:11
*/
public interface UserRepository extends CrudRepository<User, Long> {
/**
* 根据名字查询用户列表
* @param name
* @return
*/
List<User> findByName(String name);
/**
* 根据用户的邮箱和用户名查询
* @param email
* @param name
* @return
*/
List<User> findByEmailAndName(String email, String name);
}
完成controller层的搭建
package com.echo.example.example.controller;
import com.echo.example.example.entity.User;
import com.echo.example.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* author:XLecho
* Date:2018/10/25 0025
* Time:19:12
*/
@RestController
@RequestMapping(path = "/demo")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addUser(@RequestParam(value = "name") String name,
@RequestParam(value = "email") String email) {
User user = new User();
user.setEmail(email);
user.setName(name);
userRepository.save(user);
}
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<User> getAllUser(){
return (List<User>) userRepository.findAll();
}
}
到这里位置,其实我们已经完成了jpa与数据库的基本交互。那么我们可以运行工程,然后使用postman调用即可(这里不演示)