pom.xml
<!-- 数据库依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- JPA框架 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.yml
server:
port: 8888
spring:
application:
name: node09-boot-jpa
datasource:
url: jdbc:mysql://127.0.0.1:3306/tutu?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
User findByAge(Integer age);
User findByNameAndAge(String name, Integer age);
@Query("from User u where u.name=:name")
User findSql(@Param("name") String name);
}
UserService.java
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
@Resource
private UserRepository userRepository ;
// 保存
public void addUser (User user){
userRepository.save(user) ;
}
// 根据年龄查询
public User findByAge (Integer age){
return userRepository.findByAge(age) ;
}
// 多条件查询
public User findByNameAndAge (String name, Integer age){
return userRepository.findByNameAndAge(name,age) ;
}
// 自定义SQL查询
public User findSql (String name){
return userRepository.findSql(name) ;
}
// 根据ID修改
public void update (User user){
userRepository.save(user) ;
}
//根据id删除一条数据
public void deleteStudentById(Integer id){
userRepository.deleteById(id);
}
}