pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
实体类:
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
private String address;
public Person() {
super();
}
public Person(Long id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Dao类:
@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {
List<Person> findByName(String name);
List<Person> findByAddress(String address);
List<Person> findByNameAndAddress(String name,String address);
@Query("select p from Person p where p.name=:name and p.address=:address")
List<Person> withNameAndAddressQuery(@Param("name")String Name,@Param("address")String address);
}
controller:
@RestController
@SpringBootApplication
public class SpringBootSampleMysqlApplication {
@Autowired
PersonRepository dao;
@RequestMapping("/get")
public Person getP(String name){
Person person = dao.findByName(name).get(0);
return person;
}
@RequestMapping("/getByAddress")
public List<Person> getByAddress(String address){
List<Person> list = dao.findByAddress(address);
return list;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootSampleMysqlApplication.class, args);
}
}
测试:
![11636334-301b7616a7bfd079](https://i-blog.csdnimg.cn/blog_migrate/d8d242ae8fab56d8b693d92aa43591bd.webp?x-image-process=image/format,png)
image