JPA使用学习
Posted laoxia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JPA使用学习相关的知识,希望对你有一定的参考价值。
1、添加相关jar包:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-jpa</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>mysql</groupId> 7 <artifactId>mysql-connector-java</artifactId> 8 </dependency>
2、添加配置文件:
1 spring: 2 datasource: 3 url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true 4 username: root 5 password: root 6 driver-class-name: com.mysql.cj.jdbc.Driver
3、添加实体类:
1 @Entity 2 public class User implements Serializable 3 private static final long serialVersionUID = 1L; 4 5 @Id 6 @GeneratedValue 7 private Long id; 8 9 @Column(nullable = false, unique = true) 10 private String name; 11 12 @Column(nullable = false) 13 private Integer age; 14 15 @Column(nullable = false, unique = true) 16 private String email; 17 18 public User() 19 super(); 20 21 22 public User(String name, Integer age, String email) 23 this.name = name; 24 this.age = age; 25 this.email = email; 26 27 28 ........... 29 30
4、实现Repository类:
1 public interface UserRepository extends JpaRepository<User, Long> 2 3 User findByName(String name); 4 5 User findByNameOrEmail(String name, String email); 6 7
5、controller实现:
1 @Autowired 2 private UserRepository userRepository; 3 4 @RequestMapping("/getUsers") 5 public List<User> getUsers() 6 List<User> users=userRepository.findAll(); 7 return users; 8
6、多表联合查询:
1 @Query("select h.city as city, h.name as name, avg(r.rating) as averageRating " 2 - "from Hotel h left outer join h.reviews r where h.city = ?1 group by h") 3 Page<HotelSummary> findByCity(City city, Pageable pageable); 4 5 @Query("select h.name as name, avg(r.rating) as averageRating " 6 - "from Hotel h left outer join h.reviews r group by h") 7 Page<HotelSummary> findByCity(Pageable pageable);
7、参考资料:
http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html
http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html
以上是关于JPA使用学习的主要内容,如果未能解决你的问题,请参考以下文章