推荐专栏:Spring Data JPA 实战
推荐:Spring Data JPA 查询方法那些事【全面】
Spring配置:Spring Data JPA入门简解与XML配置实现
详细:SpringBoot整合SpringData与JPA
CREATE TABLE `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `UK_USER_NAME` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
一路单击 Next 按钮,然后完成得到一个工程,完成后如下结构:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
若运行后报【java.sql.SQLException: The server time zone value ‘�й���ʱ��’ is unrecognized…】错误,则应在url后加【&serverTimezone=UTC】
package top.actim.springdata.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity // 实体(表名)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id // 主键 及 生成策略
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
private String username;
private String password;
public User() {
}
public User(int uid, String username, String password) {
this.uid = uid;
this.username = username;
this.password = password;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
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;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
package top.actim.springdata.dao;
import org.springframework.data.repository.CrudRepository;
import top.actim.springdata.pojo.User;
// 继承CrudRepository接口,<实体类, 主键类型>
// JPA根据实体类的类名去对应表名(可以使用@Entity的name属性?@Table进行修改)
public interface UserRepository extends CrudRepository<User, Integer> {
}
package top.actim.springdata.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.actim.springdata.dao.UserRepository;
import top.actim.springdata.pojo.User;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(path = "/add")
@ResponseBody
public User addNewUser(@RequestParam String username, @RequestParam String password) {
User n = new User();
n.setUsername(username);
n.setPassword(password);
userRepository.save(n);
return n;
}
@GetMapping(path = "/all")
@ResponseBody
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
}
package top.actim.springdata;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringdataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringdataApplication.class, args);
}
}
http://localhost:8080/user/all
http://localhost:8080/user/add?username=First&password=First
#注意唯一性约束
JPA常见注解及使用 || JPA之常用 基本注解
理解JPA注解@GeneratedValue的使用方法:主键策略生成器
1、常用基本注解
@Entity
@Table
@Basic
@Column
@GeneratedValue
@Id2、特殊注解
@Transient
@Temporal
用 table 来生成主键
SpringData 方法定义规范
https://www.jianshu.com/p/9d199ae05467
https://blog.csdn.net/Reward_GC/article/details/86643737
Spring Data JPA方法名命名规则
Spring Data JPA 查询方法那些事【详细::】
Spring Data JPA之JpaSpecificationExecutor复杂动态查询实例
Spring Data JPA【JpaSpecificationExecutor】动态查询示例
参考文章:SpringData_Repository接口概述
Spring Data JPA几个核心接口【详细】
Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,
开发者需要在自己定义的接口中声明需要的方法
public interface Repository{ } Spring Data可以让我们只定义接口,只要遵循 Spring Data的规范,就无需写实现类。
与继承 Repository 等价的一种方式,就是在持久层接口上使用 @RepositoryDefinition 注解,并为其指定 domainClass 和 idClass 属性。两种方式是完全等价的Repository 的子接口
基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:
1.Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类2.CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法
3.PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法
4.JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法
5.自定义的 XxxxRepository 需要继承 JpaRepository,这样的 XxxxRepository 接口就具备了通用的>数据访问控制层的能力。
6.JpaSpecificationExecutor: 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法
JPA接口命名常用关键字
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 ages) … where x.age in ?1 NotIn findByAgeNotIn(Collection age) … 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)