SpringBoot+IDEA+maven+SpringDataJPA的简单案例使用

SpringBoot+IDEA+maven+SpringDataJPA的简单案例使用

步骤:
1.1 引入依赖
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!--jpa依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
1.2 修改配置
#Spring boot视图配置
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
#静态文件访问配置
spring.mvc.static-path-pattern=/static/**

#数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/myspringboot2?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=lbl123...
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
1.3 数据库建表

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-if3FL98E-1603444980654)(E:\笔记\Typora\SpringBoot的使用\image-20201023160911929.png)]

分析:depart与employee的关系是多对一,反之则一对多。

1.4 编写entity类关系

Employee类

package com.lbl.springboot_lab06.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "employee")
public class Employee{
    @Id
    private int id;
    private String name;
    private int age;
    //外键的字段不需要添加到该类的属性中,只需将关联的类引入即可
    //多对一的关系用@ManyToOne注解,fetch为加载方式,targetEntity表示该类关联哪个类,即数据库中该表与哪个表关联。
    @ManyToOne(fetch= FetchType.LAZY,targetEntity = Depart.class)	
    //name代表本表的外键,referencedColumnName表示被关联的表的字段。
    @JoinColumn(name ="depart_id",referencedColumnName = "depart_no")	
    private Depart depart;
}

Depart类

package com.lbl.springboot_lab06.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "depart")
public class Depart {
    @Id
    @Column(name = "depart_no")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int departNo;
    @Column(name = "depart_name")
    private String departName;
	//一对多的关系只需用个集合即可
    @OneToMany(fetch = FetchType.LAZY,targetEntity = Employee.class)
    private Set<Employee> employees=new HashSet<>();

}
1.5 编写dao类
package com.lbl.springboot_lab06.repository;

import com.lbl.springboot_lab06.bean.Depart;
import com.lbl.springboot_lab06.bean.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

//需要继承JpaRepository类
public interface EmployeeRepository extends JpaRepository<Employee,Integer> {
	//@Query()注解为自定义SQL查询语句,?1代表第一个参数。
    @Query("select s from  Employee s where s.depart.departName=?1")
    List<Employee> findEmployeesByDepart_Name(String dname);

    //:depart_name代表绑定的参数
    @Query("select s from Employee s where s.depart.departName=:depart_name and s.age<:age")
    List<Employee> findIdAndNameByDepart_NameAndAge(@Param("depart_name")String dname, @Param("age")int age);
    
    //若需要使用原生SQL语句,则需要在@Query()中添加 nativeQuery = true 。
    @Query(nativeQuery = true,value = "select d.depart_name from depart d join employee e on d.depart_no=e.depart_id where e.name=?1")
    List<String> findDepart_nameByEmployeeName(String name);

    //@Query()注解默认只支持查询,若需要进行增删改操作则需添加 @Modifying,并且在service的方法中添加 @Transactional。
    @Modifying
    @Query("delete from Employee s where  s.name=?1")
    int  deleteEmployeeByEmployeeName(String employeeName);
}

1.6 编写service接口
package com.lbl.springboot_lab06.service;

import com.lbl.springboot_lab06.bean.Depart;
import com.lbl.springboot_lab06.bean.Employee;
import com.lbl.springboot_lab06.repository.DepartRepository;
import com.lbl.springboot_lab06.repository.EmployeeRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeService {
    @Resource
    private EmployeeRepository employeeRepository;
    @Resource
    private DepartRepository departRepository;

    public List<Map<String,Object>> getIdAndNameByDepart_NameAndAge(String dname, int age){
        List<Employee> es=employeeRepository.findIdAndNameByDepart_NameAndAge(dname,age);
        List<Map<String,Object>> results = new ArrayList<>();
        for (Employee e:es){
            Map<String,Object> map=new HashMap<>();
            map.put("id",e.getId());
            map.put("name",e.getName());
            map.put("age",e.getAge());
            results.add(map);
        }
        return results;
    }

    public List<String> getDepart_nameByEmployeeName(String name){
        return  employeeRepository.findDepart_nameByEmployeeName(name);
    }

    //@Transactional注解表示该调用的方法包含‘增删改’的操作
    @Transactional
    public int deleteEmployeeByEmployeeName(String employeeName){
        return  employeeRepository.deleteEmployeeByEmployeeName(employeeName);
    }

}
1.7 编写controller类
package com.lbl.springboot_lab06.controller;

import com.lbl.springboot_lab06.bean.Depart;
import com.lbl.springboot_lab06.service.EmployeeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    @Resource
    private EmployeeService employeeService ;

    @RequestMapping(value = "/index")
    public String Index(){
        return "index";
    }

    @RequestMapping(value = "/getIDAndNameByDepart_NameAndAge")
    public String getIDAndNameByDepartNameAndAge(String depart_name, String  age, HttpSession session){
        int age1= Integer.parseInt(age);
        System.out.println(depart_name+age);
        List<Map<String,Object>> em =employeeService.getIdAndNameByDepart_NameAndAge(depart_name,age1);
        session.setAttribute("employees",em);
        System.out.println(em);
        return "employee";

    }
    
    @RequestMapping(value = "/getDepart_nameByName")
    public String getDepartByName(String name,HttpSession session){
        List<String> em=employeeService.getDepart_nameByEmployeeName(name);
        System.out.println(em);
        session.setAttribute("depart",em);
        session.setAttribute("employee_name",name);
        return "depart";
    }

    @RequestMapping(value = "/deleteEmployeeByEmployeeName")
    public String deleteEmployeeByEmployeeName(String name){
        int result=employeeService.deleteEmployeeByEmployeeName(name);
        if (result == 0) {
            return "error";
        }
        System.out.println(result);
        return "delete";
    }

}
1.8 编写jsp页面

depart.jsp (其中一个页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
部门名称:<br/>

<c:forEach items="${sessionScope.depart}" var="dep">
    <tr>
        <td>${dep}</td><br/>
    </tr>
</c:forEach>

</body>
</html>

1.9 目录结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GNMhQb8z-1603444980656)(E:\笔记\Typora\SpringBoot的使用\image-20201023165015776.png)]

1.10 运行测试

先在数据库表插入几条记录:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-puIE71H7-1603444980657)(E:\笔记\Typora\SpringBoot的使用\image-20201023165721206.png)]

浏览器地址栏输入:http://localhost:8080/getDepart_nameByName?name=Ada

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IMaVBRKU-1603444980660)(E:\笔记\Typora\SpringBoot的使用\image-20201023165912904.png)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值