准备工作
1.新建数据库stu
2.建立表student
新建一个项目
1.创建实体类student
package com.kude.stu.kudestu.stu.entity;
import javax.persistence.*;
@Entity/*应用在实体类上*/
@Table(name="student")/*表示对应的表的名字*/
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) /*应用在实体类上表示id自增*/
private Integer id;
private String name;
private int age;
private String sex;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student() {
}
}
2.DAO层
package com.kude.stu.kudestu.stu.dao;
import com.kude.stu.kudestu.stu.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface StudentDao extends JpaRepository<Student,Integer> {
Student findStudentById(Integer id);
/**
* 自定义查询方法
* @param name 要查询的名字
* @return
*/
@Query(name="findStudentByName",nativeQuery = true,value = "select * from student where name=:name")
List<Student> findStudentByName(@Param("name") String name);
}
3.service层
package com.kude.stu.kudestu.stu.service;
import com.kude.stu.kudestu.stu.dao.StudentDao;
import com.kude.stu.kudestu.stu.entity.Student;