zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    什么是静态测试、动态测试、黑盒测试、白盒测试、α测试 β测试
    软件产品质量特性
    目前主要的测试用例设计方法是什么?
    软件的安全性应从哪几个方面去测试?
    软件配置管理的作用?软件配置包括什么?
    HDOJ1003(DP)
    HDOJ5650
    POJ1068(模拟)
    POJ2586(贪心)
    HDOJ1548(BFS)
  • 原文地址:https://www.cnblogs.com/laoxia/p/11427249.html
Copyright © 2011-2022 走看看