一对多关系
新建员工信息
package com.rich.springdatajpa.controller;
import com.rich.springdatajpa.entity.Dept;
import com.rich.springdatajpa.entity.Emp;
import com.rich.springdatajpa.repository.DeptRepository;
import com.rich.springdatajpa.repository.EmpRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
@RestController
//@Controller
// 使用@RestController的时候默认所有方法都返回JSON字符串,
/// 而不是跳转页面,我们也不用在方法上写@ResponseBody
@RequestMapping("/emp")
//默认该类的所有方法都开启事务
@Transactional(rollbackFor = Exception.class)
public class EmpController {
@Autowired
private EmpRepository empRepository;
@Autowired
private DeptRepository deptRepository;
@GetMapping("/{id}")
public Emp findById(@PathVariable("id") Integer id){
return empRepository.findById(id).get();
}
@GetMapping("/create")
public Emp create(){
Emp emp = new Emp();
emp.setComm(0f);
emp.setEname("laoqi");
emp.setHiredate(new Date());
emp.setJob("Teacher");
emp.setMgr(null);
emp.setSal(0f);
Dept d = deptRepository.findById(20).get();
emp.setDept(d);
empRepository.save(emp);
return emp;
}
需求 根据部门编号查询所有员工的信息
Repository 文件实现
public interface EmpRepository extends JpaRepository<Emp,Integer> {
//select * from emp where deptno = ?
@Query("select e from Emp e where e.dept.deptno=:dn")
public List<Emp> findEmps(@Param("dn") Integer deptno);
}
controller文件实现
@GetMapping("/find")
public List<Emp> find(Integer deptno){
return empRepository.findEmps(deptno);
}
验证代码
在浏览器中输入 http://localhost:8089/emp/find?deptno=20