1、maven引入jar包(jpa和mysql)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver server.port=8080
3、创建实体类(示例)
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable; @Entity
@Table(name="student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer sid;
private String sname;
private Integer sage;
private String ssex; public Integer getSid() {
return sid;
} public void setSid(Integer sid) {
this.sid = sid;
} public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} public Integer getSage() {
return sage;
} public void setSage(Integer sage) {
this.sage = sage;
} public String getSsex() {
return ssex;
} public void setSsex(String ssex) {
this.ssex = ssex;
}
}
4、创建对应实体的接口
import com.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
//1、这个类中自带一些简单的增删改查方法,可以直接调用
public interface StudentRepository extends JpaRepository<Student,Integer> { /*2、也支持执行sql语句(例如)*/
@Query("from Student where sage = ?1")
List<Student> getStudentsBySage(@Param("sage") Integer sage); /*3、支持根据方法名的查询(例如)*/
Student findBySid(Integer sid); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
详细介绍:
https://blog.csdn.net/ityouknow/article/details/52688664