码迷,mamicode.com
首页 > 其他好文 > 详细

JPA使用学习

时间:2019-08-29 00:09:37      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:utc   text   under   class   pre   int   control   cte   font   

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使用学习

标签:utc   text   under   class   pre   int   control   cte   font   

原文地址:https://www.cnblogs.com/laoxia/p/11427249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!