使用springboot+springdata-jpa+前台Html页面实现增删改查

大部分注解都打了注释,希望这篇对你们有用哦~ 谢谢!

首先在实体类

@Data //自动封装getset方法
@Entity // 表示这是给实体
@Table(name = "students") // 表名 会生成表数据
public class Student {
    @Id //主键
    @GeneratedValue(strategy= GenerationType.IDENTITY) // 自增列
    private Long id;

	//字段名,可以不写
    @Column(name = "name",columnDefinition = "varchar(25) comment '姓名'") 				
    private String name;

    @Column
    private String sex;

    private Integer gradeId;
}

Dao层

//extends JpaRepository 继承jpa自有的东西,里面有很多方法
public interface StudentDao extends JpaRepository<Student,Long> {

	//@Query 可以自己写sql语句 ,nativeQuery = true 多表时使用
    @Query(value = "select * from students where name like concat('%',?,'%') ",nativeQuery = true)
    List<Student> findByName(String name);

}

servlce

public interface StudentService {

    /**
     * 新增
     */
    Student savn(Student student);

    /**
     * 修改
     */
    Student update(Student student);

    /**
     * 分页查询
     */
    Page<Student> findByPage(Integer pageNum,Integer size,Student student);

    /**
     * 删除
     */
    void del(Long id);

    /**
     * 根据名字查询
     */
    List<Student> findByName(String name);

    /**
     * 根据id查询
     * @param id
     * @return
     */
    Student findById(Long id);
  

Impl 实现类

@Service
public class StudentServlceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

	//这是新增时 id 不重复 可以不写
    @Autowired
    private IdWorker idWorker;


    @Override
    public Student savn(Student student) {
        //UUID
        //把新增的对象返回给调用者
        //分布式服务的时候很多时候会自己设置Id
        student.setId(idWorker.nextId());

        Student s = studentDao.save(student);
        return s;
    }

    @Override
    public Student update(Student student) {
        return studentDao.save(student);
    }

    @Override
    public Page<Student> findByPage(Integer pageNum, Integer size,Student student) {
        if (pageNum==null || pageNum <=0){
            pageNum=1;
        }
        //模糊查询然后分页 
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
                .withIgnorePaths("sex")
                .withIgnorePaths("gradeId")
                .withIgnorePaths("id");
        Example<Student> example = Example.of(student, matcher);
        PageRequest of = PageRequest.of(pageNum - 1, 2);

        Page<Student> pages = studentDao.findAll(example,of);

        return pages;
    }

    @Override
    public void del(Long id) {
        studentDao.deleteById(id);
    }

    @Override
    public List<Student> findByName(String name) {
        return studentDao.findByName(name);
    }

    @Override
    public Student findById(Long id) {
        return studentDao.findById(id).get();
    }

controller

@Controller
public class StudentController {

	//自动注入 都知道的吧!!!
    @Autowired
    private StudentService studentService;

    @GetMapping("/findbypage")
    public String findbypage(Integer pageNum,Integer size, Model model,Student student){
        Page<Student> byPage = studentService.findByPage(pageNum,size,student);
        model.addAttribute("stu",byPage);//分页查询
        model.addAttribute("likename",student.getName()); //根据名字查询
        return "index";
    }


    @RequestMapping("/add")
    public String add(Student student){
         studentService.savn(student);
        System.out.println("新增成功!");
        //重定向
        return "redirect:/findbypage";
    }

    @RequestMapping("/detele/{id}")
    public String del(@PathVariable Long id){
        studentService.del(id);
        return "redirect:/findbypage";
    }

    @RequestMapping("/dita")
    public String getid(Long id,Model model){
        if (id!=null){
            Student byId = studentService.findById(id);
            model.addAttribute("stu",byId);
        }
        return "Add";
    }

    @RequestMapping("/update")
    public String update(Student student){
        studentService.update(student);
        return "redirect:/findbypage";
    }



配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  jpa:
    show-sql: true  #显示sql语句
    hibernate:
      ddl-auto: update
      naming:
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    database: mysql #配置现在所使用的数据库

前台html


<html  lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8" />
		<title>title>
	head>
	<body>
	<form action="/findbypage" method="get">
		姓名:<input type="text" name="name" th:value="${likename==null}?'':${likename}">
		<input type="submit">
	form>

				<table border="1" cellspacing="0" cellpadding="20">
						<tr>
						<td>编号td>
						<td>名字td>
						<td>性别td>
						<td>年级td>
						<td>操作td>
					tr>

						<tr th:each="student:${stu}"> 
							<td th:text="${student?.id}">td>
							<td th:text="${student?.name}">td>
							<td th:text="${student?.sex}">td>
							<td th:text="${student?.gradeId}">td>
							<td><a href="" th:href="@{/detele/}+${student?.id}">删除a>
								<a th:href="@{/dita/(id=${student.id})}">修改a>
							td>
						tr>
				table>
            <a href="/dita">新增信息a>
            <a th:href="@{/findbypage(pageNum=1)}">首页a>
            <a th:href="@{/findbypage(pageNum=${stu?.number+1}-1)}">上一页a>
            <a th:href="@{/findbypage(pageNum=${stu?.number+1}+1)}">下一页a>
            <a th:href="@{/findbypage(pageNum=${stu?.totalPages})}">尾页a>
	body>
html>



<form th:action="${stu==null}?@{/add}:@{/update}">
    <table>
        <tr>
            <p><td><input type="hidden" name="id"/>td>p>
            <p><td>姓名:<input type="text" name="name" th:value="${stu?.name}"/>td>p>
            <p> <td>性别:<input type="text" name="sex" th:value="${stu?.sex}"/>td>p>
            <p><td>年级编号:<input type="text" name="gradeId" th:value="${stu?.gradeId}"/>td>p>
            <td><input type="submit"/>td>

        tr>
    table>
form>


再会!⭐

你可能感兴趣的:(使用springboot+springdata-jpa+前台Html页面实现增删改查)