SpringBoot 提供的JPARepository基本满足我们的业务需求,不要写sql语句,自己也可以写方法,名字按jpa的命名格式即可
此测试采用 MySQL 数据库+idea工具
首先新建一个springboot数据库
maven配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot
username: ***
password: ***
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
说明(此处百度去看)
show-sql: true 打印出sql语句
jpa.hibernate.ddl-auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:
·create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表 哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
·create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
·update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),
以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。
要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
具体代码
1.User实体对象
这个会自动生成user表,和hibernate框架一样
@Entity
@Data //自带get,set
@Component
public class User {
@Id //主键
@GeneratedValue // 自增
private Integer id;
private String name;
private Integer age;
}
2.新建一个JPARepository
UserRepository 继承 JpaRepository 即可
public interface UserRepository extends JpaRepository<User,Integer>{
// Integer 是id的类型
// User 是返回的对象
// 根据年龄查询
List<User> findByAge(Integer age);
}
3.controller类
@RestController
public class JpaController {
@Autowired
private UserRepository userRepository;
@GetMapping("/hello")
public String hello(){
System.out.println("JpaController.hello 11111");
return "public String hello()";
}
/**
* <p>获取所有用户</p>
* @return
*/
@GetMapping("/users")
public List<User> getUsers(){
return userRepository.findAll();
}
/**
* <p>添加一个用户</p>
* @return
*/
@PostMapping("/add")
public Message<User> addUser(@Valid User user){
userRepository.save(user);
return "";
}
/**
* <p>查询某个用户</p>
* @param id
* @return
*/
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id){
User one = userRepository.findOne(id);
return one;
}
/**
* <p>删除某个用户</p>
* @param id
*/
@DeleteMapping("/user/{id}")
public void delUser(@PathVariable("id") Integer id){
userRepository.delete(id);
}
/**
* <p>修改某个用户信息</p>
* @param id
* @param name
* @param age
* @return
*/
@PutMapping("/user/{id}")
public User updateUser(@PathVariable("id") Integer id,
@RequestParam("name") String name,
@RequestParam("age") Integer age){
User user = new User();
user.setId(id);
user.setAge(age);
user.setName(name);
return userRepository.save(user);
}
/**
* <p>根据年龄查询</p>
* @param age
* @return
*/
@GetMapping("/user/age/{age}")
public List<User> findByAge(@PathVariable("age") Integer age){
List<User> byAge = userRepository.findByAge(age);
return byAge;
}
}
说明
根据年龄查询是自己写的方法,在UserRepository 按它的格式来就可以
到这里user表的增删改查就都有了,有些方法的注解可以不合理,LZ只是想测试一下更多的注解而已
Keyword(关键字) | Sample(命名) | JPQL snippet(sql示例) |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = 1? |
Between | findByStartDateBetween | … where x.startDate between 1? and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
推荐 博客 https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa/index.html