Spring Data JPA
JPA(Java Persistence API)是 Sun 官⽅方提出的 Java 持久化规范。它为 Java 开发⼈人员提供了了⼀一种对象 / 关联映射⼯工具来管理理 Java 应⽤用中的关系数据。它的出现主要是为了了简化现有的持久化开发⼯工作和整合 ORM 技术,结束现在 Hibernate、 TopLink、 JDO 等 ORM 框架各⾃自为营的局⾯面。
Spring Data JPA 是 Spring 基于 ORM 框架、 JPA 规范的基础上封装的⼀一套 JPA 应⽤用框架,可以让开发者⽤用极简的代码即可实现对数据的访问和操作。它提供了了包括增、删、改、查等在内的常⽤用功能,且易易于扩展,学习并使⽤用 Spring Data JPA 可以极⼤大提⾼高开发效率。 Spring Data JPA 其实就是 Spring 基于 Hibernate 之上构建的 JPA 使⽤用解决⽅方案,⽅方便便在 Spring Boot 项⽬目中使⽤用 JPA 技术。
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/news?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: *
jpa:
hibernate:
ddl-auto: update
use-new-id-generator-mappings: false
show-sql: true
thymeleaf:
mode: HTML
profiles:
active: dev
实体类
@Entity
@Table(name="t_user")
public class User {
@Id //主键标识
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String username;
private String password;
private String email;
private String avatar;
private String nickname;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
private Integer type;
@Temporal(TemporalType.TIMESTAMP) //指定时间格式
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
@OneToMany(mappedBy = "user")//一对多
private List<News> newsList= new ArrayList<>();
//getter&setter&toString
}
@Entity
@Table(name = "t_type")
public class Type {
@Id //主键标识
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "分类名称不能为空")
private String name;
@OneToMany(mappedBy = "type")
private List<News> newsList = new ArrayList<>();
public Type(){
}
//getter&setter&toString
}
Repository
public interface UserRepository extends JpaRepository<User,Long> {
User findByUsernameAndPassword(String username, String password);
}
public interface TypeRepository extends JpaRepository<Type,Long> {
Type findByName(String name);
}
Service
public interface UserService {
User checkUsers(String username, String Password);
}
public interface TypeService {
Page<Type> listType(Pageable pageable);
Type saveType(Type type);
Type getTypeByName(String name);
void delete(Long id);
Type getType(Long id);
Type updateType(Long id, Type type);
}
@Service
public class UserServiceImpl implements UserService
{
@Autowired
public UserRepository userRepository;
@Override
public User checkUsers(String username, String password)
{
return userRepository.findByUsernameAndPassword(username, password);
}
}
@Service
public class TypeServiceImpl implements TypeService
{
@Autowired
private TypeRepository typeRepository;
@Override
public Page<Type> listType(Pageable pageable) {
return typeRepository.findAll(pageable);
}
@Override
public Type saveType(Type type) {
return typeRepository.save(type);
}
@Override
public Type getTypeByName(String name) {
return typeRepository.findByName(name);
}
@Override
public void delete(Long id) {
typeRepository.deleteById(id);
}
@Override
public Type getType(Long id) {
return typeRepository.findById(id).orElse(null);
}
@Override
public Type updateType(Long id, Type type) {
Type type1 = typeRepository.findById(id).orElse(null);
if(type1==null){
System.out.println("未获取更新对象");
return null;
}
BeanUtils.copyProperties(type,type1);
return typeRepository.save(type1);
}
}
Controller
@Controller
@RequestMapping("/admin")
public class LoginController {
@Autowired
private UserService userService;
@GetMapping
public String loginPage(){
return "admin/login";
}
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password,
HttpSession session, RedirectAttributes attributes){
User user = userService.checkUsers(username,password);
if(user!=null){
user.setPassword(null);
session.setAttribute("user",user);
return "admin/index";
}else {
attributes.addFlashAttribute("message","用户名或密码错误");
return "redirect:/admin";
}
}
@GetMapping("/logout")
public String logout(HttpSession session){
session.removeAttribute("user");
return "redirect:/admin";
}
}
@Controller
@RequestMapping("/admin")
public class TypeController {
@Autowired
private TypeService typeService;
@RequestMapping("types")
public String type(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC)
Pageable pageable, Model model){
model.addAttribute("page",typeService.listType(pageable));
return "admin/types";
}
@GetMapping("/types/input")
public String input(Model model){
model.addAttribute("type",new Type());
return "admin/types-input";
}
@PostMapping("/types/add")
public String add(@Valid Type type, BindingResult result, RedirectAttributes attributes){
System.out.println(type);
Type type1 = typeService.getTypeByName(type.getName());
if(type1!=null){
result.rejectValue("name","nameError","不能添加重复的分类");
}
if(result.hasErrors()){
return "admin/types-input";
}
Type type2 = typeService.saveType(type);
if(type2==null){
attributes.addFlashAttribute("message","新增失败");
}else{
attributes.addFlashAttribute("message","新增成功");
}
return "redirect:/admin/types";
}
@RequestMapping("/types/{id}/delete")
public String delete(@PathVariable Long id,RedirectAttributes attributes){
typeService.delete(id);
attributes.addFlashAttribute("message","删除成功");
return "redirect:/admin/types";
}
@RequestMapping("/types/{id}/toUpdate")
public String toUpdate(@PathVariable Long id,Model model){
model.addAttribute("type",typeService.getType(id));
return "admin/types-input";
}
@RequestMapping("/types/update/{id}")
public String update(@Valid Type type,@PathVariable Long id,BindingResult result,RedirectAttributes attributes){
System.out.println("type"+type);
Type type1 = typeService.getTypeByName(type.getName());
if(type1!=null){
result.rejectValue("name","nameError","不能添加重复的分类");
}
if(result.hasErrors()){
return "admin/types-input";
}
Type type2 = typeService.updateType(id, type);
if(type2==null){
attributes.addFlashAttribute("message","更新失败");
}else{
attributes.addFlashAttribute("message","更新成功");
}
return "redirect:/admin/types";
}
}